<?php
namespace Admin\Frontend\Controllers;

use \Admin\Frontend\Controllers\ControllerBase;
use Admin\Models\bpm\XHBpmTransList;
use Admin\Models\crm\XhcustInfo;
use Admin\Models\faq\XhfaqInfo;
use Admin\Models\hrm\XhhrmDepart;
use Admin\Models\hrm\XhhrmStaff;
use Admin\Models\ims\XHImsApplyTablet;
use Admin\Models\ims\XHImsBoxIn;
use Admin\Models\ims\XHImsBoxOut;
use Admin\Models\ims\XHImsProdType;
use Admin\Models\ims\XHImsProduce;
use Admin\Models\ims\XHImsProduct;
use Admin\Models\ims\XHImsReceive;
use Admin\Models\ims\XHImsReturn;
use Admin\Models\log\XhlogCommit;
use Admin\Models\overt\XhovertFeedback;
use Admin\Models\res\XhresQuestionbank;
use Admin\Models\res\XhresQuestionbankcontact;
use Admin\Models\res\XhresReferenceApply;
use Admin\Models\res\XhresReferencePlan;
use Admin\Models\school\XhschoolInfo;
use Admin\Models\server\XhserverBox;
use Admin\Models\stats\XhstatsBrushgroup;
use Admin\Models\sys\XhsysClassification;
use Admin\Models\sys\XhsysEnum;
use Admin\Models\track\XhtrackTask;
use Admin\Models\user\XhsysUserpower;
use Helpers\Area;
use Helpers\Assets;
use Helpers\File;
use Helpers\User;
use Helpers\UserPower;
use Helpers\Cache;
use Helpers\HttpClient;
use Helpers\Main;
use Admin\Models\user\XhsysUser;
use Helpers\Tool;
use Helpers\XhException;
use Modules\Lm;
use Lm\Models\XHLmGoodsType;
use Modules\School;
use Phalcon\Db\Adapter\Pdo\Mysql;
use Phalcon\Mvc\Controller;
use Phalcon\Mvc\Model\Resultset;

use Admin\Models\sys\XhsysTree;
use Admin\Models\sys\XhsysPower;
use Admin\Models\sys\XhsysFunction;
use Services\App;
use Services\Box;
use Admin\Models\device\XhdeviceBoxInfo;
use Admin\Models\device\XhsysDevicerepair;
use Admin\Models\device\XhsysDevicerepairDelay;
use Admin\Models\res\Books;
use Admin\Models\device\XhsysUsertablet;
use Admin\Models\log\LoginLog;

class HelpController extends ControllerBase
{

    public function testAction()
    {
        $this->view->pick('help/test');
//        $this->assets->addJs('assets/axios/dist/axios.min.js');
        Assets::toast();
    }

    public function uploadFileAction()
    {
        try {
            switch ($this->request->getPost('type')) {
                case 1:
                    $file = $_FILES['file'];
                    $info = File::upload($file, 'sys', 'test');
                    break;
                case 2:
                    $file = $this->request->getUploadedFiles()[0];
                    $info = File::upload($file, 'sys', 'test');
                    break;
                case 3:
                    $file = $this->request->getUploadedFiles()[0];
                    $path = Tool::buildPath(TEMP_PATH, $file->getName());
                    $file->moveTo($path);
                    $info = File::upload($path, 'sys', 'test');
                    break;
                default:
                    return $this->sendErrorResponse(400, '不支持改类型上传');
            }
//        $info = [
//            'id' => '',
//            'url' => '',
//            'name' => '',
//            'size' => '',
//            'md5' => '',
//        ];
            return $this->sendJsonResponse($info);
        } catch (\Exception $e) {
            return $this->sendErrorResponse(500, '系统异常', $e->getMessage());
        }
    }

    public function runAction()
    {
        $command = $this->request->getRawBody();
        eval($command);
        die;
    }

    public function checkStatusAction()
    {
        $result = [];

        //session
        try {
            $this->session->set('testSession', 'success');
            $result['session'] = $this->session->get('testSession') ? 'success' : 'fail';
        } catch (\Exception $e) {
            $result['session'] = 'fail';
        }

        //memcache
        try {
            Cache::save('testCache', 'success');
            $result['memcache'] = Cache::get('testCache') ? 'success' : 'fail';
        } catch (\Exception $e) {
            $result['memcache'] = 'fail';
        }

        //mysql
        try {
            $mysql = $this->db->fetchOne('select * from XHSys_User limit 1');
            $result['mysql'] = $mysql ? 'success' : 'fail';
        } catch (\Exception $e) {
            $result['mysql'] = 'fail';
        }

        //写入权限
        try {
            $result['write'] = file_put_contents(CACHE_PATH . '/test.log', 'testWrite') ? 'success' : 'fail';
        } catch (\Exception $e) {
            $result['write'] = 'fail';
        }

        return $this->sendJsonResponse($result);
    }

    public function synTreeAction()
    {

    }

    public function ztyDownAction()
    {
        if (Tool::getValue(Main::getConfigByName('admin'), 'ztyLogin', 'true') == 'true' && !User::isLogin()) {
            Main::goLoginPage();
        }
        $apps = App::getApplications(1, 10, ['keywords' => '智通云'])['rows'];
        if (!$apps) {
            return $this->sendViewError('找不到应用');
        }
        $type = [
            1 => '(学生端)',
            2 => '(教师端)',
        ];
        foreach ($apps as $app) {
            $url  = end($app['appVersions'])['url'];
            $name = $app['name'] . $type[$app['userType']];
            echo "<a href='{$url}'>{$name}</a><br /><br />";
        }
        die;
    }

    /**
     * 检查http参数
     *
     * @param $code
     *
     * create by ck 20170322
     */
    public function checkHttpAction($code = 200)
    {
        ignore_user_abort(false);
        $this->view->disable();
        $data = [
            'headers' => $this->request->getHeaders(),
            'body' => $this->request->getRawBody(),
            'post' => $this->request->getPost(),
            'get' => $this->request->getQuery(),
            'method' => $this->request->getMethod(),
            'hasFile' => $this->request->hasFiles()
        ];
        if ($this->request->hasFiles()) {
            $file = $this->request->getUploadedFiles()[0];
            $data['file']['error'] = $file->getError();
            $data['file']['tempName'] = $file->getTempName();
            $data['file']['extension'] = $file->getExtension();
            $data['file']['size'] = $file->getSize();
            $data['file']['name'] = $file->getName();
            $data['file']['key'] = $file->getKey();
            $data['file']['realType'] = $file->getRealType();
            $data['file']['type'] = $file->getType();
        }
//        sleep(4);
//        $logger = new \Phalcon\Logger\Adapter\File(BASE_PATH . "/public/logs/test.log");
//        $logger->info('test');
        $this->response->setStatusCode($code)->setJsonContent($data)->send();
    }

    public function checkAction()
    {

    }

    /**
     * 刷新memcache
     *
     * create by ck 20170322
     */
    public function flushMemcacheAction()
    {
        if (Cache::flush()) {
            echo '缓存刷新成功！';
        } else {
            echo '缓存刷新失败！';
        }
        die;
    }

    public function phpinfoAction()
    {
        echo phpinfo();
        die;
    }

    public function debugAction($type = 'debugbar')
    {
        $debug = Tool::getValue($_SESSION, 'DEBUG', []);
        if (Tool::getValue($debug, 'mode', '')) {
            unset($_SESSION['DEBUG']);
            die('debug关闭');
        }
        $_SESSION['DEBUG'] = ['mode' => $type];
        die($type . '开启');
    }

    /**
     * 上传应用并自动发布
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20170727
     * modify by ck 20170818    可更新应用组应用
     */
    public function releaseAppAction()
    {
        //获取学校id，判断是否需要更新应用组应用
        $schoolId = $this->request->get('schoolid', 'int');

        //初始化控制器并执行上传方法
        $appController = new AppserverController();
        $appController->initialize();
        $appData = $appController->uploadApplicationAction()->getContent();
        $appData = json_decode($appData, true);
        if (isset($appData['error'])) {
            return $this->response->setJsonContent($appData, JSON_UNESCAPED_UNICODE);
        }

        //合并参数，提交
        $_POST = array_merge($appData, $this->request->get());
        if (!$schoolId) {
            return $appController->releaseApplicationAction();
        }
        $result = $appController->releaseApplicationAction()->getContent();
        $result = json_decode($result, true);
        if (isset($result['error'])) {
            return $this->response->setJsonContent($result, JSON_UNESCAPED_UNICODE);
        }

        //更新应用组应用
        $response = $appController->httpClient->put(sprintf(
            '/api/v1/initiate/apps/%s/versions/%s/to/groups?schoolId=%s',
            $appData['packageName'],
            $appData['versionCode'],
            $schoolId
        ));
        if (!$response->isSuccess()) {
            $body = $response->toObject();
            return $this->response->setStatusCode(500)
                ->setJsonContent(['code' => 500, 'error' => '更新到应用组失败！', 'msg' => $body->msg ?: $response]);
        }
        return $this->response->setJsonContent(['msg' => '成功！'], JSON_UNESCAPED_UNICODE);
    }


    public function synQuestionBankAction()
    {
        $this->view->setMainView('');
        $this->view->pick('help/index');
        if (!$this->request->isPost()) {
            return $this->flash->notice('请输入题库ID以同步...');
        }
        $needId = $this->request->getPost('needId', 'int');
        $sourceId = $this->request->getPost('sourceId', 'int');
        if (!$needId || !$sourceId) {
            return $this->flash->error('参数不完整！');
        }
        if (!in_array($needId, [143, 145, 146, 147, 148, 149, 150, 151, 152])) {
            return $this->flash->error('需同步ID超出范围！');
        }
        $needRs = XhresQuestionbank::findFirst($needId);
        if (!$needRs) {
            return $this->flash->warning('不存在目标题库信息！');
        }
        $sourceRs = XhresQuestionbank::findFirst($sourceId);
        if (!$sourceRs) {
            return $this->flash->warning('不存在数据源题库信息！');
        }
        $sourceArr = $sourceRs->toArray();
        unset($sourceArr['iQBankId'], $sourceArr['sBookName'], $sourceArr['tCreateDate'], $sourceArr['iCreateUserId']);
        $result = $needRs->update($sourceArr);
        if (!$result) {
            return $this->flash->error('同步失败！');
        }
        XhresQuestionbankcontact::refreshBookshelfByQuestionBankId($needId);
        return $this->flash->success('同步成功！');
    }

    public function getQBankInfoAction($id)
    {
        $this->view->disable();
        $bank = XhresQuestionbank::findFirst($id);
        if (!$bank) {
            return $this->response->setJsonContent(['error' => 'wrong id'])->send();
        }
        return $this->response->setJsonContent($bank->toArray())->send();
    }

    public function dealSchoolCodeAction()
    {
        $codeInfo = '{"XH00001":"奉化市实验中学","XH00002":"杭师大附属仓前实验中学","XH00003":"杭州市采荷中学","XH00004":"杭州市余杭区仁和中学","XH00005":"余杭区塘栖第二中学","XH00006":"余姚市世南中学","XH00007":"西湖第一实验学校","XH00008":"绍兴市元培中学","XH00009":"宁波市奉化区西坞中学","XH00010":"奉化锦屏中学","XH00011":"三门县实验初级中学","XH00012":"三门县浦坝港镇小雄初级中学","XH00013":"平阳县昆阳镇第二中学","XH00014":"金华市第四中学","XH00015":"杭州市余杭区运河中学","XH00016":"余杭区太炎中学","XH00017":"杭州绿城育华学校","XH00018":"杭州丁兰实验中学","XH00019":"椒江区第二中学","XH00020":"椒江区下陈中学","XH00021":"舟山市普陀第二中学","XH00022":"三门县城关中学","XH00023":"象山县丹城第二中学","XH00024":"磐安县实验初级中学","XH00025":"宁波区奉化区城北中学","XH00026":"浙工大附属实验学校","XH00027":"天台县赤城中学","XH00028":"三门县沿江中学","XH00029":"杭州风帆中学","XH00030":"绍兴鲁迅外国语学校","XH00031":"宁波市奉化区溪口中学","XH00032":"象山县荔港学校","XH00033":"象山县石浦中学","XH00034":"象山县鹤浦中学","XH00035":"缙云县东渡镇东渡初级中学","XH00036":"杭州文澜中学","XH00037":"缙云县湖川初级中学","XH00038":"浙江省温州市第十二中学","XH00039":"余姚市舜水中学","XH00040":"余姚市梨洲中学","XH00041":"三门县六敖中学","XH00042":"三门县花桥中学","XH00043":"临海市杜桥镇中学","XH00045":"平阳实验中学","XH00049":"台州市路桥二中","XH00051":"温岭市第四中学","XH00052":"台州市书生小学","XH00053":"嘉善泗洲中学","XH00054":"杭州西溪中学","XH00056":" 嘉兴市南湖区城南中学","XH00058":"嘉兴王店镇中学","XH00059":"嘉兴余新镇中学","XH00060":"兰溪市实验中学","XH00061":"东阳市吴宁三中教育集团汉宁校区","XH00064":"临海市桃渚中学","XH00065":"平湖行知中学","XH00066":"杭州四季青中学","XH00068":"东北师大南湖实验学校","XH00069":"湖州白雀学校","XH00071":"盐官镇初级中学","XH00073":"温州市永嘉县城关中学","XH00074":"衢州市新星初级中学","XH00075":"浙江师范大学附属衢州白云学校","XH00079":"高桥金帆实验学校","XH00080":"萧山区靖江镇初级中学","XH00081":"海宁市硖石中学","XH00083":"海宁市南苑中学","XH00084":"大唐镇中","XH00086":"平阳县鳌江镇第八中学","XH00087":"三门县泗淋中学","XH00088":"三门县高枧中学","XH00090":"杭州二中白马湖学校","XH00091":"上海外国语大学附属浙江宏达学校","XH00092":"桐庐叶浅予学校","XH00095":"重庆市铜梁区巴川初级中学校","XH00096":"德清二中","XH00097":"武康中学","XH00098":"湖州五中余家漾校区","XH00099":"桐庐实验初级中学","XH00100":"杭州天目双语实验学校","XH00103":"杭州市余杭区五常中学","XH00104":"永嘉东方外国语学校","XH00106":"义乌市佛堂镇初级中学","XH00107":"浙江省临海市涌泉中学","XH00108":"义乌市后宅中学","XH00109":"慈溪市新世纪实验学校","XH00112":"萧山区金惠初级中学","XH00116":"赤岸镇初级中学","XH00117":"三门县珠岙中学","XH00118":"椒江第五中学","XH00119":"舟山市普陀区东港中学","XH00121":"舟山绿城育华(国际)学校初中部","XH00122":"舟山绿城育华(国际)学校高中部","XH00123":"舟山绿城育华（国际）学校小学部","XH00124":"海盐县实验中学","XH00127":"杭州师范大学附属桐乡市实验中学","XH00128":"建德市梅城初级中学","XH00129":"缙云县壶滨初级中学","XH00130":"象珠镇清溪初级中学","XH00132":"宁海县西店镇初级中学","XH00134":"玉环县楚门二中","XH00136":"缙云县东方中学","XH00139":"北大新世纪温州附属学校","XH00145":"丽水花园中学","XH00156":"杭州市采荷中学濮家校区","XH00157":"余姚市三七市镇中学","XH00158":"闲林中学","XH00159":"王店镇建设中学","XH00160":"丰潭中学","XH00161":"桐庐县城关初级中学","XH00162":"衢州书院中学","XH00163":"浙江省缙云中学","XH00164":"永康市第四中学","XH00167":"杭州市文溪中学","XH00169":"浙江省缙云县实验中学","XH00172":"南京师范大学附属中学新城初级中学","XH00178":"江山市贺村初级中学","XH00179":"松阳县第三中学","XH00206":"湖州五中凤凰校区","XH00207":"湖州五中仁皇山校区","XH00208":"宁海县黄坛镇中学","XH00209":"大桥中学","XH00210":"黄岩东浦中学","XH00211":"杭州保俶塔实验学校（本部）","XH00212":"杭州保俶塔申花实验学校","XH00213":"德清四中","XH00214":"寿昌初级中学","XH00215":"建德市大同初级中学","XH00216":"建德大慈岩初级中学","XH00217":"余姚市姚江中学","XH00218":"三墩中学","XH00219":"嘉兴运河实验学校","XH00220":"山东省潍坊第十中学","XH00221":"重庆市第110中学校","XH00222":"临海城西中学","XH00223":"海宁长安镇初级中学","XH00224":"南京师范大学盐城实验学校","XH00225":"嘉兴一中实验学校","XH00226":"桐庐三合中学","XH00227":"临海市回浦实验中学","XH00228":"余姚市陆埠镇中学","XH00229":"萧山区城南初级中学","XH00230":"建德三都初级中学","XH00231":"临海上盘中学","XH00232":"莲都区碧湖中学","XH00233":"清远市清城中学","XH00234":"余姚市河姆渡镇中学","XH00235":"嘉兴平湖市东湖中学东方校区","XH00236":"龙泉市顺风实验学校","XH00237":"余姚市阳明中学","XH00238":"杭州东方中学","XH00239":"莲都区城中中学","XH00240":"萧山区河上镇初级中学","XH00241":"绍兴马山中学","XH00242":"嘉兴新塍镇中学","XH00243":"嘉善第一中学","XH00244":"嘉善第四中学","XH00245":"建德乾潭初级中学","XH00246":"江山淤头初级中学","XH00247":"江山坛石初中","XH00248":"江山新塘边初中","XH00249":"江山石门初中","XH00250":"建德航头初级中学","XH00251":"嘉兴洪兴实验","XH00252":"仙桥初级中学","XH00253":"富阳市银湖中学","XH00254":"建德大洋初级中学","XH00255":"丽水市松阳县汇文中学","XH00256":"江山峡口初中","XH00257":"磐安县新城中学","XH00258":"象山县新桥学校","XH00259":"三门县海游初级中学","XH00260":"江山城东实验初中","XH00261":"新市镇初级中学","XH00262":"江山上余初中","XH00263":"文元教育集团云和县育英外国语实验学校","XH00264":"重庆南岸区茶园新城中学","XH00265":"重庆市丰都县平都中学校","XH00266":"嘉兴平湖市东湖中学育才校区"}';
        $codeInfo = json_decode($codeInfo, true);
        $message = [];
        $success = 0;
        foreach ($codeInfo as $code => $name) {
            $school = XhschoolInfo::findFirst([
                'conditions' => 'bDelete = 0 AND sSchoolName = :name:',
                'bind' => ['name' => $name]
            ]);
            if (!$school) {
                $message[] = "{$name}({$code})找不到对应学校";
                continue;
            }
            $school->sCode = $code;
            if (!$school->save()) {
                $message[] = "{$name}({$code})保存失败";
            }
            $success++;
        }
        echo "共", count($codeInfo), '条记录，成功', $success, '条...<br />';
        echo implode('<br />', $message);
        die;
    }

    public function dealPowerAction()
    {
        $arr = [
            ['Config_ConfigList' => 'Config_List'],
            ['User_UserList' => 'User_List'],
            ['School_StudentList' => 'School_Stud'],
            ['School_TeacherList' => 'School_Tch'],
            ['App_AppList' => 'App_List'],
            ['Ask_QuestionList' => 'Ask_Question'],
            ['Ask_SurveyList' => 'Ask_Survey'],
            ['Log_ManageErrorList' => 'Log_Error'],
            ['Log_ManageCommitList' => 'Log_Commit'],
            ['Log_AppErrorList' => 'Log_AppError'],
            ['Log_AppLocateList' => 'Log_AppLocate'],
            ['Server_MicroServerList' => 'Server_MicroServer'],
            ['Server_BoxList' => 'Server_Box'],
            ['Res_App_RPackList' => 'Res_App_RPack'],
            ['Read_ArticleList' => 'Read_Article'],
            ['Read_ColumnList' => 'Read_Column'],
            ['Read_MarkerList' => 'Read_Marker'],
            ['Device_registerList' => 'Device_Register'],
        ];
        foreach ($arr as $old => $new) {
            $powers = XhsysPower::find([
                'conditions' => 'sPowerTag like :old:',
                'bind' => ['old' => "{$old}%"]
            ]);
            foreach ($powers as $power) {
                $power->sPowerTag = str_replace($old, $new, $power->sPowerTag);
                echo $power->sPowerTag . ($power->save() ? '成功' : '失败');
                echo '<br />';
            }
            $userPowers = XhsysUserpower::find([
                'conditions' => 'mUPowerTag like :old:',
                'bind' => ['old' => "{$old}%"]
            ]);
            foreach ($userPowers as $userPower) {
                $userPower->mUPowerTag = str_replace($old, $new, $userPower->mUPowerTag);
                echo $userPower->iUPUserId . '：' . $old . ($userPower->save() ? '成功' : '失败');
                echo '<br />';
            }
        }
        die('执行完毕！');
    }

    public function flushCppUserAction()
    {
        $refreshUserConfig = Main::getConfigByName('cRelation');
        if (isset($refreshUserConfig['refreshUser']) && !empty($refreshUserConfig['refreshUser'])) {
            echo file_get_contents($refreshUserConfig['refreshUser']);
//            echo '<br />' . @file_get_contents($refreshUserConfig['refreshGw']);
        }
    }

    public function synUserAction()
    {
        try {
            $oldDB = new Mysql(Main::getConfigByName('oldCenterDB'));
            $oldMaxUserId = $oldDB->fetchOne('select max(us_id) as maxId from users')['maxId'];
            echo '老库最大id：' . $oldMaxUserId . '<br />';
            $newMaxUserId = $this->db->fetchOne('select max(iUserId) as maxId from XHSys_User')['maxId'];
            echo '新库最大id：' . $newMaxUserId . '<br />';
            $userInfoSql = "select iUserId,sLogonName,sUserName,iUserType,iSchoolId,sLogonPwd,tCreateDate,sAdClsName,sSelfPhone from XHSys_User where iUserId > {$oldMaxUserId}";
            $userInfo = $this->db->fetchAll($userInfoSql);
            if (!$userInfo) {
                echo '无最新用户信息！sql：' . $userInfoSql . '<br />';
                die;
            }
            $success = 0;
            foreach ($userInfo as $info) {
                $oldField = [
                    'us_id'         => $info['iUserId'],
                    'us_uid'        => $info['sLogonName'],
                    'us_name'       => $info['sUserName'],
                    'us_flag'       => $info['iUserType'],
                    'us_school_xxid'=> $info['iSchoolId'],
                    'us_passwd'     => $info['sLogonPwd'],
                    'us_date'       => $info['tCreateDate'],
                    'us_szbj'       => $info['sAdClsName'] ?: '',
                    'us_tel'        => $info['sSelfPhone'] ?: '',
                    'us_csrq' => '0000-00-00',
                    'us_xb' => '',
                    'us_mz' => '',
                    'us_bmdq' => '',
                    'us_sdxx' => '',
                    'us_sdnj' => '',
                    'us_qq' => '',
                    'us_fmxm' => '',
                    'us_jtgddh' => '',
                    'us_fmsj' => '',
                    'us_jtdz' => '',
                    'us_fmdw' => '',
                    'us_dwdz' => '',
                    'us_bzsm' => '',
                    'us_ord' => 0,
                    'us_sskm' => '',
                    'us_lastip' => '',
                    'us_question' => '',
                    'us_answer' => '',
                    'us_lxxx' => '',
                    'us_gsbz' => '',
                    'us_us_id_power' => '',
                    'us_province' => '',
                    'us_city1' => '',
                    'us_city2' => '',
                    'us_fw_text' => '',
                    'us_fdq_name' => '',
                    'us_sfzx' => '',
                    'us_us_id_power_ls' => '',
                    'us_jf_dates' => '0000-00-00 00:00:00',
                    'us_sq_dl_dates' => '0000-00-00 00:00:00',
                    'us_sq_ls_dates' => '0000-00-00 00:00:00',
                    'us_sales_sort' => '',
                    'us_sq_fl_dates' => '0000-00-00 00:00:00',
                    'us_fmsjm' => '',
                    'us_xyh' => '',
                    'us_domain' => '',
                    'us_nickname' => '',
                    'us_email' => '',
                    'us_czy_id' => 0,
                ];
                $result = $oldDB->insertAsDict('users', $oldField);
                if ($result) {
                    $success++;
                }
                else {
                    echo '插入失败：' . json_encode($info, JSON_UNESCAPED_UNICODE);
                }
            }
            echo '执行完毕,成功插入' , $success , '条！';
            die;
//            $oldDbConfig = Main::getConfigByName('oldCenterDB', true);
////            $tempConn = new Mysql($oldDbConfig);
////            $diffIdArr = $tempConn->fetchAll('select us_id from users where us_id not in (select iUserId from xh_webmanage.XHSys_User)');
//            $diffIdArr = $this->db->fetchAll("select us_id from {$oldDbConfig['dbname']}.users where us_id not in (select iUserId from xh_webmanage.XHSys_User) and us_uid not in (select sLogonName from xh_webmanage.XHSys_User where sLogonName is not null) group by us_uid");
//            $diffIdArr = array_column($diffIdArr, 'us_id');
//            if (empty($diffIdArr)) die('无差异，不需要同步！');
//            $diffIdArr = implode(',', $diffIdArr);
//            $this->db->execute('SET NAMES "latin1"');
//            $userInfo = $this->db->fetchAll("SELECT us_id,us_name,us_uid,us_passwd,us_tel,us_flag,us_xb,us_school_xxid,us_sdnj,us_szbj,us_sskm,us_mz,sPortrait,sMotherPhone,sFatherPhone,sOtherPhone,iFirstPhone,us_date FROM {$oldDbConfig['dbname']}.users WHERE us_id IN ({$diffIdArr})");
//            $this->db->execute('SET NAMES "utf8"');
//            $insertSql = 'INSERT INTO XHSys_User (iUserId,sUserName,sLogonName,sLogonPwd,sSelfPhone,iUserType,iUserSex,iSchoolId,iGradeCode,sAdClsName,sSubject,sNationName,sPortrait,sMotherPhone,sFatherPhone,sOtherPhone,iFirstPhone,bCompany,bDisable,bOldData,bDelete,tCreateDate,iCreateUserId,tLastModifyDate,iLastModifyUserId,sRoles,bCompleted,bMobileVerified) VALUES ';
//            $valueArr = [];
//            $nowTime = date('Y-m-d H:i:s');
//            $userId = Main::getLoginUserInfo('userId');
//            $userId or $userId = 1;
//            foreach ($userInfo as $user) {
//                $user['us_passwd'] = strlen($user['us_passwd']) == 32 ? $user['us_passwd'] : strtoupper(md5($user['us_passwd']));
//                $user['us_xb'] = $user['us_xb'] == '男' ? 1 : ($user['us_xb'] == '女' ? 2 : 0);
//                $user['us_sdnj'] = UserController::getGradeCode($user['us_sdnj']);
//                $roles = self::getRoles($user['us_flag']);
//                $valueArr[] = "('{$user['us_id']}','{$user['us_name']}','{$user['us_uid']}','{$user['us_passwd']}','{$user['us_tel']}','{$user['us_flag']}','{$user['us_xb']}','{$user['us_school_xxid']}','{$user['us_sdnj']}','{$user['us_szbj']}','{$user['us_sskm']}','{$user['us_mz']}','{$user['sPortrait']}','{$user['sMotherPhone']}','{$user['sFatherPhone']}','{$user['sOtherPhone']}','{$user['iFirstPhone']}',0,0,1,0,'{$user['us_date']}','{$userId}','{$nowTime}','{$userId}','{$roles}',1,1)";
//            }
//            $insertSql .= implode(',', $valueArr);
//            $this->db->query($insertSql) or die('插入失败！');
//            echo '执行成功！成功插入' . count($valueArr) . '条';
        } catch (\Exception $e) {
            echo '错误：' . $e->getMessage();
        }
    }

    private static function getRoles($userType)
    {
        switch ($userType) {
            case 1:
                return 'student';
            case 2:
                return 'assistant';
            case 3:
                return 'agent';
            case 4:
                return 'teacher';
            case 5:
                return 'parents';
            case 6:
                return 'school_admin';
            case 7:
                return 'staff';
            case 8:
                return 'admin';
            default:
                return '';
        }
    }

    public function flushLoginSchoolAction()
    {
        $url = Main::getConfigByName('cLogin')['url'];
        if (!$url) die('缺少配置路径');
        echo file_get_contents(rtrim($url, '/') . '/refreshSchInfo?K={"V":0}');
        die;
    }

    /**
     * 导出用户信息
     *
     * @param null $key
     * @param null $limit
     *
     * create by ck 20170417
     */
    public function exportUserInfoAction($key = null, $limit = null)
    {
        $this->view->disable();
        set_time_limit(0);
        $key == 'xuehai1234' or die;
        $conditions = [
            'columns' => 'iUserId,sUserName,sLogonName,iSchoolId',
            'order' => 'iUserId desc'
        ];
        if ($limit) $conditions['limit'] = $limit;
        if ($this->request->getQuery('userType')) {
            $conditions['conditions'] = 'iUserType = ' . $this->request->getQuery('userType', 'int');
        }
        $userInfo = XhsysUser::find($conditions)->toArray();
        Tool::exportExcelOnline('userInfo', ['用户ID', '用户姓名', '账号', '学校ID'], $userInfo, 'csv');
    }

    public function studTempStatsAction()
    {
        $this->view->setMainView('');
        $this->view->pick('help/studTempStats');
        $this->tag->setTitle('沿江-吴志强-科刷统计');
        if (!$this->request->isPost()) {
            return $this->flash->success('请选择日期...');
        }
        try {
            $startDate = $this->request->getPost('startDate', 'string');
            $endDate = $this->request->getPost('endDate', 'string');
            if (!$startDate || !$endDate) {
                return $this->flash->error('日期不能为空！');
            }
            $startDate .= ' 00:00:00';
            $endDate .= ' 23:59:59';
            $examId = 240;
            $courseId = 37;
            $studId = 53820;
            $dbName = '';
            $schoolDB = Main::getSchoolMainDB(4104, $dbName);
            $courseDBName = $dbName . '_course' . $courseId;
            $examDBName = $dbName . '_exam' . $examId;

            $tree = $tmpTree = $total = [];

            //处理章节
            $treeArr = $schoolDB->fetchAll("SELECT a.ad_id1 as id,a.ad_name as name,a.ad_parentid as parentId,count(b.ho_id) as queNum,count(DISTINCT(c.li_ho_id)) as wareNum from {$examDBName}.address_items_tree_user a LEFT JOIN {$examDBName}.homework_list_base b on a.ad_id = b.ho_ad_id LEFT JOIN xh_zjtzsmyjzx_school_exam240.list_courseware c on b.ho_id = c.li_ho_id GROUP BY a.ad_id");
            $this->dealExamTree($tmpTree, $treeArr);
            $this->sortExamTree($tree, $tmpTree);

            //做题情况
            $brushInfo = $schoolDB->fetchAll("select uc_ad_id as adId,count(uc_ho_id) as brushNum,sum(uc_score > 0) as rightNum,round(sum(uc_score > 0)/count(uc_ho_id) * 100, 1) as rightRate,count(DISTINCT(uc_ho_id)) as brushRealNum from {$courseDBName}.st_upload_content where uc_us_id = {$studId} and uc_date >= '{$startDate}' and uc_date <= '{$endDate}' GROUP BY uc_ad_id");

            //合并数据
            $tree = array_column($tree, null, 'id');
            foreach ($brushInfo as $row) {
                if (isset($tree[$row['adId']])) {
                    $tree[$row['adId']] = array_merge($tree[$row['adId']], $row);
                    $total['queNum'] += $tree[$row['adId']]['queNum'];
                    $total['wareNum'] += $tree[$row['adId']]['wareNum'];
                    $total['rightNum'] += $row['rightNum'];
                    $total['brushNum'] += $row['brushNum'];
                    $total['brushRealNum'] += $row['brushRealNum'];
                }
            }

            //错题重做情况
            $wrongInfo = $schoolDB->fetchAll("select uc_ad_id as adId,count(uc_ho_id) as brushWrongNum from {$courseDBName}.st_upload_content where uc_us_id = {$studId} and uc_ho_id in (select uc_ho_id from {$courseDBName}.st_upload_content where uc_us_id = {$studId} and uc_score <= 0) GROUP BY uc_ad_id");
            foreach ($wrongInfo as $row) {
                if (isset($tree[$row['adId']]) && $tree[$row['adId']]['brushNum']) {
                    $tree[$row['adId']]['brushWrongNum'] = $row['brushWrongNum'];
                    $total['brushWrongNum'] += $tree[$row['adId']]['brushWrongNum'];
                }
            }

            //错题微课数量
            $wrongWareInfo = $schoolDB->fetchAll("select a.uc_ad_id as adId,count(b.li_id) as wareWrongNum from {$courseDBName}.st_upload_content a LEFT JOIN {$examDBName}.list_courseware b on a.uc_ho_id = b.li_ho_id where a.uc_us_id = {$studId} and a.uc_score <= 0 GROUP BY a.uc_ad_id");
            foreach ($wrongWareInfo as $row) {
                if (isset($tree[$row['adId']]) && $tree[$row['adId']]['brushNum']) {
                    $tree[$row['adId']]['wareWrongNum'] = $row['wareWrongNum'];
                    $total['wareWrongNum'] += $tree[$row['adId']]['wareWrongNum'];
                }
            }

            $total['rightRate'] = round(($total['rightNum'] / $total['brushNum']) * 100, 1);

            return $this->view->setVars([
                'tree' => array_values($tree),
                'total' => $total
            ]);
        } catch (\Exception $e) {
            return $this->flash->error($e->getMessage());
        }
    }

    private function dealExamTree(&$tree, &$title)
    {
        if (empty($tree)) {
            foreach ($title as $key => $val) {
                if ($val['parentId'] == 0) {
                    $tree[] = [
                        'id' => intval($val['id']),
                        'name' => $val['name'],
                        'queNum' => $val['queNum'],
                        'wareNum' => $val['wareNum']
                    ];
                    unset($title[$key]);
                    $this->dealExamTree($tree, $title);
                }
            }
        } else {
            foreach ($tree as $treeKey => $treeVal) {
                foreach ($title as $key => $val) {
                    if ($val['parentId'] == $treeVal['id']) {
                        $tree[$treeKey]['child'][] = [
                            'id' => intval($val['id']),
                            'name' => $val['name'],
                            'queNum' => $val['queNum'],
                            'wareNum' => $val['wareNum']
                        ];
                        unset($title[$key]);
                    }
                }
                if (isset($tree[$treeKey]['child'])) {
                    $this->dealExamTree($tree[$treeKey]['child'], $title);
                }
            }
        }
    }

    private function sortExamTree(&$newTree, $treeArr, $link = '')
    {
        $newLink = $link . '&#12288;&#12288;';
        foreach ($treeArr as $tree) {
            $temp = $tree;
            unset($temp['child']);
//            $temp['que'] = $temp['img'] = $temp['char'] = $temp['charReal'] = $temp['imgChar'] = '';
            $temp['name'] = $link . $temp['name'];
            $newTree[] = $temp;
            if (isset($tree['child'])) {
                $this->sortExamTree($newTree, $tree['child'], $newLink);
            }
        }
    }

    public function feedbackListAction($page = 1)
    {
        $pageSize = $this->request->get('rows', 'int', 200);
        $appCode = $this->request->get('appCode', 'string');
        $parameters = [
            'order' => 'iFBId DESC',
            'limit' => [
                'number' => $pageSize,
                'offset' => ($page - 1) * $pageSize
            ]
        ];
        if ($appCode) {
            $parameters['conditions'] = "iAppCode = '{$appCode}'";
        }
        $rows = XhovertFeedback::find($parameters);
        $rows or die('<div class="alert alert-notice"><p>无数据</p></div>');
        $tableStr = '';
        $tableStr .= "<link rel='stylesheet' href='{$this->url->getBaseUri()}assets/bootstrap/bootstrap.min.css'>";
        $tableStr .= "<style>body{padding: 30px;word-break: break-all;}th{min-width: 100px;}</style>";
        $tableStr .= "<script type='application/javascript' src='{$this->url->getBaseUri()}assets/jquery/jquery.min.js'></script>";
        $tableStr .= "<script type='application/javascript' src='{$this->url->getBaseUri()}assets/bootstrap/bootstrap.min.js'></script>";
        $tableStr .= '<table class="table table-hover">';
        $tableStr .= '<tr class="info">';
        foreach ($rows[0] as $key => $value) {
            if ($key == 'sContent') {
                $tableStr .= "<th>{$key}</th>";
                continue;
            }
            $tableStr .= "<th>{$key}</th>";
        }
        $tableStr .= '</tr>';
        foreach ($rows as $row) {
            $tableStr .= '<tr>';
            foreach ($row as $value) {
                $tableStr .= "<td>{$value}</td>";
            }
            $tableStr .= '</tr>';
        }
        $tableStr .= '</table>';
        return $this->response->setContent($tableStr);
    }

    public function dealStaffAccountAction()
    {
        set_time_limit(0);
        $httpClient = new HttpClient('http://common.yunzuoye.net/overt');
//        $httpClient = new HttpClient('http://zt.yunzuoye.net:84/apps/overt');
        $powerUserArr = $this->db->fetchAll('select iUPUserId,sUserName from XHSys_UserPower LEFT JOIN XHSys_User ON iUPUserId = iUserId where IFNULL(mUPowerTag, "") <> "" ');
        if (!$powerUserArr) {
            die ('找不到用户权限信息！');
        }
        $powerUserArr = array_column($powerUserArr, 'iUPUserId', 'sUserName');
        $staffArr = $this->db->fetchAll('select iStaffId,sStaffName,sSelfPhone FROM XHHrm_Staff where bDelete = 0 and IFNULL(iUserId, "") = ""');
        $result = [];
        foreach ($staffArr as $staff) {
            if (!$staff['sStaffName']) {
                $result[] = '姓名为空：' . implode(' || ', $staff);
                continue;
            }
            if (isset($powerUserArr[$staff['sStaffName']])) {
                $op = $this->db->execute("update XHHrm_Staff set iUserId = {$powerUserArr[$staff['sStaffName']]} where iStaffId = {$staff['iStaffId']}");
                $result[] = $staff['sStaffName'] . '关联' . ($op ? '成功' : '失败') . '：' . $powerUserArr[$staff['sStaffName']];
                continue;
            }
            $user = XhsysUser::findFirst(["sSelfPhone = '{$staff['sSelfPhone']}' or sLogonName = '{$staff['sSelfPhone']}'"]);
            if ($user) {
                $op = $this->db->execute("update XHHrm_Staff set iUserId = {$user->iUserId} where iStaffId = {$staff['iStaffId']}");
                $result[] = $staff['sStaffName'] . '关联' . ($op ? '成功' : '失败') . '：' . $user->iUserId;
                continue;
            }
            $K = ['sSelfPhone' => $staff['sSelfPhone'], 'sUserName' => $staff['sStaffName'], 'sLogonPwd' => strtoupper(md5('123456'))];
            $response = $httpClient->post('main/register-staff', ['K' => json_encode($K)]);
            $body = $response->toObject();
            $result[] = $staff['sStaffName'] . '创建:' . $body->M;
        }
        echo implode('<br />', $result);
        die;
    }

//    public function addStaffPowerAction($departName = null, $powerNames = null)
//    {
////        $departPowerList = [
////            '市场部' => [
////                'Stats',
////                'Stats_App',
////                'Bpm',
////                'Bpm_Plan',
////                'Bpm_Plan_Edit',
////                'Cust',
////                'Cust_List',
////                'Cust_List_Add',
////                'Cust_List_Edit',
////                'Cust_List_Del',
////                'Cust_List_Follow',
////                'Cust_List_Follow_Add',
////                'Cust_List_Follow_Edit',
////                'Cust_List_Follow_Del',
////                'Cust_List_Intention',
////                'Cust_List_Intention_Add',
////                'Cust_List_Intention_Edit',
////                'Cust_List_Intention_Del',
////                'Cust_List_Cooperate',
////                'Cust_List_Cooperate_Add',
////                'Cust_List_Cooperate_Edit',
////                'Cust_List_Cooperate_Del',
////                'Cust_List_Operation',
////                'Cust_List_Operation_Add',
////                'Cust_List_Operation_Edit',
////                'Cust_List_Operation_Del',
////                'Cust_List_Contact',
////                'Cust_List_Contact_Add',
////                'Cust_List_Contact_Edit',
////                'Cust_List_Contact_Del',
////            ],
////            '运营部' => [
////                'Stats',
////                'Stats_App',
////                'Bpm',
////                'Bpm_Plan',
////                'Bpm_Plan_Edit',
////                'Read',
////                'Read_Comment',
////                'Read_Comment_Edit',
////                'Read_Comment_Del',
////                'Track',
////                'Track_Confirm',
////                'Track_Demand',
////                'Track_Demand_Add',
////                'Track_Demand_Edit',
////                'Track_Demand_Del',
////                'Track_BUG',
////                'Track_BUG_Add',
////                'Track_BUG_Edit',
////                'Track_BUG_Del',
////                'Track_Res',
////                'Track_Res_Add',
////                'Track_Res_Edit',
////                'Track_Res_Del',
////            ]
////        ];
////        foreach ($departPowerList as $departName => $powerList) {
//        if (!$departName) {
//            die('部门名称不能为空！');
//        }
//        if (!$powerNames) {
//            die('添加权限不能为空！');
//        }
//        $powerList = explode(',', $powerNames);
//        $depart = XhhrmDepart::findFirst([
//            'conditions' => 'bDelete = 0 AND sDepName = :depName:',
//            'bind' => ['depName' => $departName]
//        ]);
//        if (!$depart) {
//            echo $departName . ' 部门未找到！<br />';
////                continue;
//        }
//        $userInfo = XhhrmStaff::find([
//            'columns' => 'iUserId,sStaffName',
//            'conditions' => "sDepIds like :depId: AND iUserId is not null",
//            'bind' => ['depId' => "%{$depart->iDepId}%"]
//        ]);
//        foreach ($userInfo as $user) {
//            $userPower = XhsysUserpower::findFirst('iUPUserId = ' . $user->iUserId);
//            if (!$userPower) {
//                $userPower = new XhsysUserpower();
//                $userPower->iUPUserId = $user->iUserId;
//            }
//            $powerTags = $userPower->mUPowerTag ? explode(',', $userPower->mUPowerTag) : [];
//            foreach ($powerList as $power) {
//                if (!in_array($power, $powerTags)) {
//                    $powerTags[] = $power;
//                }
//            }
//            $userPower->mUPowerTag = implode(',', $powerTags);
//            $result = $userPower->save();
//            echo "{$user->sStaffName}({$user->iUserId}):" . ($result ? '成功' : '失败') . '<br />';
//        }
////        }
//        echo '添加权限执行结束！';
//        die;
//    }
//
//    public function delStaffPowerAction($departName = null, $powerNames = null)
//    {
//        if (!$departName) {
//            die('部门名称不能为空！');
//        }
//        if (!$powerNames) {
//            die('删除权限不能为空！');
//        }
//        $powerList = explode(',', $powerNames);
//        $depart = XhhrmDepart::findFirst([
//            'conditions' => 'bDelete = 0 AND sDepName = :depName:',
//            'bind' => ['depName' => $departName]
//        ]);
//        if (!$depart) {
//            echo $departName . ' 部门未找到！<br />';
//        }
//        $userInfo = XhhrmStaff::find([
//            'columns' => 'iUserId,sStaffName',
//            'conditions' => "sDepIds like :depId: AND iUserId is not null",
//            'bind' => ['depId' => "%{$depart->iDepId}%"]
//        ]);
//        foreach ($userInfo as $user) {
//            $userPower = XhsysUserpower::findFirst('iUPUserId = ' . $user->iUserId);
//            if (!$userPower) {
//                echo "{$user->sStaffName}({$user->iUserId}):" . '尚未有权限<br />';
//                continue;
//            }
//            $powerTags = $userPower->mUPowerTag ? explode(',', $userPower->mUPowerTag) : [];
//            foreach ($powerList as $power) {
//                $index = array_search($power, $powerTags);
//                if ($index !== false) {
//                    unset($powerTags[$index]);
//                }
//            }
//            $userPower->mUPowerTag = implode(',', $powerTags);
//            $result = $userPower->save();
//            echo "{$user->sStaffName}({$user->iUserId}):" . ($result ? '成功' : '失败') . '<br />';
//        }
//        echo '删除权限执行结束！';
//        die;
//    }

//    public function dealBrushGroupAction()
//    {
//        $groups = XhstatsBrushgroup::find([
//            'conditions' => 'bDelete = 0 AND mStandard is null'
//        ]);
//        $success = $fail = 0;
//        foreach ($groups as $group) {
//            $group->mStandard = [
//                'topicExec' => $group->iTopicExecStandard,
//                'topicExecUp' => $group->iTopicExecUpStandard,
//                'topicExecDown' => $group->iTopicExecDownStandard,
//                'rightRate' => $group->iRightRateStandard,
//                'rightRateUp' => $group->iRightRateUpStandard,
//                'rightRateDown' => $group->iRightRateDownStandard,
//            ];
//            if ($group->save()) {
//                $success++;
//                continue;
//            }
//            $fail++;
//        }
//        echo '共需处理', count($groups), '条信息。成功', $success, '条，失败', $fail, '条。';
//        die;
//    }

    //    public function synInsideBankAction($id)
//    {
//        $this->view->disable();
//        $curl = new HttpClient();
//        $source = $curl->get('http://admin.yunzuoye.net/Help/getQBankInfo/'.$id);
//        $source = $source->body;
//        echo '数据：', $source, '<br />';
//        $source = json_decode($source,true);
//        if($source && !isset($source['error'])){
//            $new = false;
//            $bank = XhresQuestionbank::createRecord($source, $new);
//            $result = $bank->save();
//            XhresQuestionbankcontact::refreshBookshelfByQuestionBankId($id);
//            die($result ? '同步成功！' : '同步失败！');
//        }
//        die('错误!'. $source['error']);
//    }

    /*public function updateQBankMd5Action()
   {
       set_time_limit(0);
       $config = Main::getConfigByName('appParse');
       $tempPath = $config['tempPath'];
       $tempPath or $tempPath = '/Mailserver/cache/temp/';
       $qBanks = XhresQuestionbank::find([
           'columns'    => 'iQBankId,sQBDownUrl,sQBMd5',
           'conditions' => 'bDelete = 0'
       ]);
       foreach($qBanks as $qBank){
           if(!$qBank->sQBDownUrl) {
               echo "题库{$qBank->iQBankId}无下载地址，跳过<br />";
               continue;
           }
           $url = parse_url($qBank->sQBDownUrl);
           if($url['query'] == 'md5=' || empty($url['query'])){
               $filePath = $tempPath . basename($qBank->sQBDownUrl);
               file_get_contents($qBank->sQBDownUrl, $url['path']);
               $md5 = strtoupper(md5_file($filePath));
               $url = str_replace('?md5=', '', $qBank->sQBDownUrl);
               $url .= '?md5=' . $md5;
               $result = XhresQuestionbank::findFirst($qBank->iQBankId)
                   ->update(['sQBDownUrl' => $url, 'sQBMd5' => $md5]);
               if(!$result){
                   echo "题库{$qBank->iQBankId}更新url及md5失败<br />";
               }
               else{
                   echo "题库{$qBank->iQBankId}更新url及md5成功<br />";
               }
           }
//            if($qBank->sQBMd5 && empty($url['query'])) {
//                $result = XhresQuestionbank::findFirst($qBank->iQBankId)
//                    ->update(['sQBDownUrl' => $qBank->sQBDownUrl . '?md5=' . $qBank->sQBMd5]);
//                if(!$result){
//                    echo "题库{$qBank->iQBankId}更新url失败<br />";
//                }
//                else{
//                    echo "题库{$qBank->iQBankId}更新url成功<br />";
//                }
//                continue;
//            }
//            if(!$qBank->sQBMd5){
//                $filePath = $tempPath . basename($qBank->sQBDownUrl);
//                if(!file_get_contents($qBank->sQBDownUrl, $tempPath . basename($qBank->sQBDownUrl))){
//                    echo "题库{$qBank->iQBankId}下载失败<br />";
//                    continue;
//                }
//                $md5 = md5_file($filePath);
//                $result = XhresQuestionbank::findFirst($qBank->iQBankId)
//                    ->update(['sQBDownUrl' => $qBank->sQBDownUrl . '?md5=' . $md5, 'sQBMd5' => $md5]);
//                if(!$result){
//                    echo "题库{$qBank->iQBankId}更新url及md5失败<br />";
//                }
//                else{
//                    echo "题库{$qBank->iQBankId}更新url及md5成功<br />";
//                }
//                continue;
//            }

//            $url = parse_url($qBank->sQBDownUrl);
//            if(empty($url['query'])) {
//                echo "题库{$qBank->iQBankId}无参数，跳过<br />";
//                continue;
//            }
//            parse_str($url['query'], $query);
//            $result = XhresQuestionbank::findFirst($qBank->iQBankId)
//                ->update(['sQBDownUrl' => $query['fileId'], 'sQBMd5' =>  $query['md5']]);
//            if(!$result){
//                echo "题库{$qBank->iQBankId}更新失败<br />";
//            }
//            else{
//                echo "题库{$qBank->iQBankId}更新成功<br />";
//            }
       }
       echo '执行完毕！';
       die;
   }*/


//    public function flushLoginUserAction($user = 0)
//    {
//        if($user){
//            if(is_numeric($user)){
//                $userId = XhsysUser::findFirst($user)->iUserId;
//                if($userId){
//                    echo '刷新用户：ID：', $user;
//                    echo '<br />';
//                    echo Main::transitToCInterface('cLogin', 'refreshUserInfo', array('type' => 'single', 'iUserId' => $userId));
//                    echo '<br />';
//                }
//            }
//            $userId = XhsysUser::findFirst("sLogonName = '{$user}'")->iUserId;
//            if($userId){
//                echo '刷新用户：账号：', $user;
//                echo '<br />';
//                echo Main::transitToCInterface('cLogin', 'refreshUserInfo', array('type' => 'single', 'iUserId' => $userId));
//                echo '<br />';
//            }
//            $userId = XhsysUser::findFirst("sSelfPhone = '{$user}'")->iUserId;
//            if($userId){
//                echo '刷新用户：手机号：', $user;
//                echo '<br />';
//                echo Main::transitToCInterface('cLogin', 'refreshUserInfo', array('type' => 'single', 'iUserId' => $userId));
//                echo '<br />';
//            }
//            die('刷新完成！');
//        }
//        die('未输入信息！');
//    }

//    public function dealPowerTagAction()
//    {
//        $powers = XhsysPower::find([
//            'conditions' => 'sPowerTag like "App_WhiteList%"'
//        ]);
//        foreach($powers as $power){
//            $power->sPowerTag = str_replace('App_WhiteList', 'App_White', $power->sPowerTag);
//            echo $power->sPowerTag . ($power->save() ? '成功' : '失败');
//            echo '<br />';
//        }
//        die('执行完毕！');
//    }

//    public function dealEnumAction()
//    {
//        $node = XhsysTree::findFirst("sNodeName = '合作模式' and iNodeType = 2");
//        $node->sNodeName = '收费模式';
//        var_dump($node->save());
//    }

//    public function dealBoxInfoAction()
//    {
//        $boxInfo = Main::getConfigByName('cBoxInfo');
//        $boxInfo = json_decode($boxInfo['boxHisInfo'], true);
//        $time = date('Y-m-d H:i:s');
//        foreach($boxInfo as $info) {
//            if(!$info['iSchoolId']) continue;
//            $obj = new XhserverBox();
//            $obj->iSchoolId = $info['iSchoolId'];
//            $obj->sBoxIp = $info['sBoxIp'];
//            $obj->sBoxWIp = $info['sBoxWIp'];
//            $obj->sBoxVersion = $info['sBoxVersion'];
//            $obj->tStartTime = $info['sStartTime'];
//            $obj->tCreateTime = $time;
//            $obj->save();
//        }
//    }

//    public function dealReadPublishAction()
//    {
//        error_reporting(E_ERROR);
//        $this->view->disable();
//        $articleInfo = Article::find([
//            'conditions' => 'status = 1 and articleurl like "%?d=04-1"',
//        ]);
//        if(!count($articleInfo)){
//            die('无数据');
//        }
//        foreach($articleInfo as $article){
//            $article->articleurl = str_replace('?d=04-1', '?d=' . date('m-d', strtotime($article->releasetime)), $article->articleurl);
//            echo $article->id, '修改', $article->save() ? '成功！': '失败！', PHP_EOL;
//        }
//        die;
//    }


//    public function packQBankAction($ids = null)
//    {
//        ignore_user_abort(true);                    //忽略浏览器断开
//        set_time_limit(0);                          //不超时
//        $this->view->disable();
//        $ids or die;
//        $mInfo = [];
//        $questionBankIds = explode(',', $ids);
//        $packConfig = Main::getConfigByName('cPackQBank');
//        if(!is_dir($packConfig['savePath'])){
//            mkdir($packConfig['savePath'], 0777, true);
//        }
//        if (!is_writeable($packConfig['savePath'])) {
//            die('存放路径不存在或无写入权限');
//        }
//        echo '存放路径正常<br />';
//        foreach($questionBankIds as $questionBankId){
//            echo '开始打包题库' . $questionBankId . PHP_EOL;
//            $packStr = $packConfig['path'] . '/' . $packConfig['toolName'] . ' '                //打包工具路径
//                . $packConfig['sign'] . ' '                                                     //标识
//                . $packConfig['savePath'] . ' '                                                 //打包输出目录
//                . $packConfig['prefix'] . ' '                                                   //数据库前缀
//                . $questionBankId . ' '                                                         //题库ID
//                . $packConfig['mysqlQBank'] . ' '                                               //mysql题库配置
//                . $packConfig['mongoQBank'] . ' '                                               //mongo题库配置
//                . $packConfig['manageQBank'];                                                   //新后台题库数据库
//            exec($packStr, $arr, $var);
//            if($var != 0){                                                                      //执行失败，记录日志
//                die('打包工具执行失败！'. json_encode($arr));
//                continue;
//            }
//            echo '打包工具执行成功' . PHP_EOL;
//            $filePath = $packConfig['savePath'] . '/book_exam' . $questionBankId . '.100fen2';
//            $questionBank = XhresQuestionbank::findFirst($questionBankId);
//            $mInfo[] = array(
//                'iQBankId'      => $questionBankId,
//                'sQBankVersion' => $questionBank->sQBVersion,
//                'sQBankMd5'     => strtoupper(md5_file($filePath)),
//                'tPackDate'     => date('Y-m-d H:i:s'),
//                'iQBookSize'    => $questionBank->iQBookSize
//            );
//        }
//        echo '<br />', '打包结果：', json_encode($mInfo);
//    }

//    public function dealPowerTagAction()
//    {
//        $userPowers = XhsysUserpower::find();
//        foreach($userPowers as $userPower){
//            if(!$userPower->sUPowerValue) continue;
//            $powerTag = XhsysPower::find([
//                'conditions' => "iPowerValue IN ({$userPower->sUPowerValue})"
//            ]);
//            if(!$powerTag) continue;
//            $powerTag = $powerTag->toArray();
//            $powerTag = array_column($powerTag, 'sPowerTag');
//            foreach($powerTag as $index => $tag){
//                if($tag == 'Res_QBankList'){
//                    $powerTag[$index] = 'Res_QBank';
//                    $powerTag[] = 'Res_QBank_List';
//                }
//                if($tag == 'Res_QBankList_Add'){
//                    $powerTag[$index] = 'Res_QBank_Add';
//                    $powerTag[] = 'Res_QBank_List_Add';
//                }
//                if($tag == 'Res_QBankList_Edit'){
//                    $powerTag[$index] = 'Res_QBank_Edit';
//                    $powerTag[] = 'Res_QBank_List_Edit';
//                }
//                if($tag == 'Res_QBankList_Del'){
//                    $powerTag[$index] = 'Res_QBank_Del';
//                    $powerTag[] = 'Res_QBank_List_Del';
//                }
//                if($tag == 'Res_QBankList_Pack'){
//                    $powerTag[$index] = 'Res_QBank_List_Pack';
//                }
//                if($tag == 'Stats'){
//                    $powerTag[] = 'Stats_App';
//                }
//                if($tag == 'Stats_Add'){
//                    $powerTag[] = 'Stats_App_Add';
//                }
//                if($tag == 'Stats_Edit'){
//                    $powerTag[] = 'Stats_App_Edit';
//                }
//                if($tag == 'Stats_Del'){
//                    $powerTag[] = 'Stats_App_Del';
//                }
//            }
//            $userPower->mUPowerTag = implode(',', $powerTag);
//            $userPower->save();
//        }
//        echo '结束！';
//    }

//    public function findDiffPowerAction()
//    {
//        $this->view->disable();
//        $oldPower = $this->db->query("select sPowerTag from XHSys_Power_bak")->fetchAll();
//        $oldPower = array_column($oldPower, 'sPowerTag');
//        $newPower = $this->db->query("select sPowerTag from XHSys_Power")->fetchAll();
//        $newPower = array_column($newPower, 'sPowerTag');
//        echo json_encode(array_values(array_diff($oldPower, $newPower))). '<br />';
//        echo json_encode(array_values(array_diff($newPower, $oldPower)));
//    }

//    public function dealServicePowerAction()
//    {
//        $this->view->disable();
//        $userPower = XhsysUserpower::find([
//            'conditions'    => 'mUPowerTag like "%Server_MicroServerList%"'
//        ]);
//        $userPower->toArray() or die('无数据');
//        foreach($userPower as $power){
//            $powerTag = explode(',', $power->mUPowerTag);
//            $index = array_search('Server_MicroServerList', $powerTag);
//            if($index !== false){
//                $powerTag[$index] = 'Stats,Stats_App';
//            }
//            $power->mUPowerTag = implode(',', $powerTag);
//            echo $power->iUPUserId;
//            var_dump($power->save());
//        }
//        die;
////        $servicePower = json_decode('{"gmn":"957,149,3179,3576,3493,3494,3617,4107,4114,4115","xhwyz":"957","honggz":"149","wuxy":"3179","zhenglinqi":"3576","wency":"3493","kcxh":"3494","honggz":"3617","xhsl":"4107","dingjy":"4114","xhwyz":"4115","zhangfan":"845","xujian1":"828","xujian1":"829","yinping":"3496,845,828,829,3495,3613,3638,4074,4073,4075,4106,4070,4111","yinping":"3495","xujian1":"3613","liaomin":"3638","xhzr":"4074","wangyu28":"4073","wangyu28":"4075","xhwh":"4106","xhzr":"4070","xhwh":"4111","18358115964":"3189,3605,3611,4057,899,4068,4102,4101,4104,4103,4110","xhym":"3605","xhym":"3611","luoshenge":"4057","18958060052":"899","zmd":"4068","xhym":"4102","smhqjxl":"4101","xhchenj":"4104","helian":"4103","18958060052":"4110","xhyzk":"684","xhyzk":"1000","xhcjb":"3261","xhcjb":"3637","heyue1":"3577,684,1000,3261,3637,4067,3190,4095,4094","heyue1":"4067","xhyc":"3190","liuchang":"4095","liuchang":"4094"}', true);
////        foreach($servicePower as $logonName => $schoolPower){
////            $user = XhsysUser::findFirst("sLogonName = '{$logonName}'");
////            if(!$user){
////                echo $logonName, '账号不存在！<br />';
////                continue;
////            }
////            $userPower = XhsysUserpower::findFirst("iUPUserId = '{$user->iUserId}'");
////            if(!$userPower){
////                $userPower = new XhsysUserpower();
////                $userPower->iUPUserId = $user->iUserId;
////            }
////            $powerTag = explode(',', trim($userPower->mUPowerTag, ','));
////            $powerTag or $powerTag = [];
////            $powerTag[] = 'Stats';
////            $powerTag[] = 'Stats_App';
////            $userPower->mUPowerTag = implode(',', $powerTag);
//////            $power = json_encode(['school' => ['id' => $schoolPower]]);
//////            $userPower->sUExtraView = $power;
//////            $userPower->sUExtraManage = $power;
////            if($userPower->save()){
////                echo $logonName, '保存成功！<br />';
////            }
////            else{
////                echo $logonName, '保存失败！<br />';
////            }
////        }
//    }
//    public function uploadFileAction()
//    {
//        set_time_limit(0);
//        $t1 = microtime(true);
//
//        $filePath = $this->request->getQuery('path', 'string');
//        echo $filePath , '<br />';
//        is_file($filePath) or die('文件不存在！');
//        $fileConfig = Main::getConfigByName('fileServer');
//        $filePath = realpath($filePath);
//        $key = 'XHSVADTKBSCECK';
//        $md5Str = strtoupper(md5_file($filePath));
//        $uploadUrl = $fileConfig['uploadUrl'] . $key . '/' . $md5Str;
//        $ch = curl_init();
//        $post_data = array(
//            'files' => new \CURLFile($filePath)
//        );
//        curl_setopt($ch, CURLOPT_HEADER, false);
//        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
//            'md5:'. $md5Str
//        ));
//        curl_setopt($ch, CURLOPT_POST, true);
//        curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
//        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);     //不自动输出
//        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
//        curl_setopt($ch, CURLOPT_URL, $uploadUrl);
//        $info = curl_exec($ch);
//        curl_close($ch);
//        echo $info;
//
//        $t2 = microtime(true);
//        echo '内存消耗：' . memory_get_usage() . PHP_EOL;
//        echo '最大消耗：' . memory_get_peak_usage() . PHP_EOL;
//        echo '耗时：' . round($t2 - $t1, 3) . '秒' . PHP_EOL;
//    }

//    public function dealTrackSchoolIdAction($power = null)
//    {
//        if($power){
//            var_dump($this->db->execute('update XHSys_Power set sPowerName="重启任务" where sPowerTag="Track_Restart"'));
//            die;
//        }
//        $result = $this->db->execute('update XHTrack_Task set sSchoolId = CONCAT(",", sSchoolId, ",")');
//        echo '更新学校ID：';
//        var_dump($result);
//        $result = $this->db->execute('alter table XHTrack_Task add iPriority int Null');
//        echo '增加优先级：';
//        var_dump($result);
//        $result = $this->db->execute('alter table XHTrack_Task add sConfirmId varchar(255) Null');
//        echo '增加确认id：';
//        var_dump($result);
//    }

    /*public function makeExamToWordAction($examId = 0, $unitId = 0, $limit = 1000, $limit1 = 1000)
    {
        //测试数据
        set_time_limit(0);
        $this->view->disable();
        $examId or die('缺少题库ID');
        $imgBaseUrl = $this->request->getQuery('imgBase', 'string', 'http://data.yunzuoye.net');

//        $dbConfig = Main::getConfigByName('oldCenterDB');
        $conn = new Mysql([
            'host'      => '192.168.0.175',
            'username'  => 'root',
            'password'  => 'root',
            'dbname'    => 'xh_product_exam' . $examId,
            'charset'   => 'latin1'
        ]);

        $title = $conn->fetchOne("select ad_name as title from address_items_tree_user where ad_id = {$unitId}");
        $title = $title['title'];
        $title or die('该目录不存在');
        $questionArr = $conn->fetchAll("select ho_zycontent as sQueContent,ho_zytype as iQueType,ho_answer as sAnswer from homework_list_base WHERE ho_parent_id = 0 and ho_ad_id = {$unitId} limit {$limit}");
//        $questionArr = $conn->fetchAll("select ho_zycontent as sQueContent,ho_zytype as iQueType,ho_answer as sAnswer from homework_list_base WHERE ho_parent_id = 0 and ho_ad_id = {$unitId} limit {$limit},{$limit1}");
//        $questionArr = $conn->fetchAll("select ho_zycontent as sQueContent,ho_zytype as iQueType,ho_answer as sAnswer from homework_list_base WHERE ho_parent_id = 0 and ho_ad_id = {$unitId}  and ho_id =1772");
        $questionArr or die('该目录下无题目');
        //匹配img标签，将 ../ 替换为对应域名
        foreach($questionArr as $key => $question){
            $questionArr[$key]['sQueContent'] = str_replace('&gt;', '&amp;gt;', $questionArr[$key]['sQueContent']);
            $questionArr[$key]['sQueContent'] = str_replace('&lt;', '&amp;lt;', $questionArr[$key]['sQueContent']);
            preg_match_all("/<img.*?src=\"(\.\.\/.*?)\".*?>/i", $question['sQueContent'], $imgInfo);
            $imgInfo = end($imgInfo);
            if(!$imgInfo) continue;
            foreach($imgInfo as $src){
                $newSrc = str_replace('../', $imgBaseUrl . '/', $src);
                $questionArr[$key]['sQueContent'] = str_replace($src, $newSrc, $questionArr[$key]['sQueContent']);
            }

        }
        $data = [
            'compressionAlgorithm' => '',
            'docName' => $title,
            'documentType' => 'docx',
            'isCallback' => 1,
            'isCompress' => 2,
            'isProcessingStyle' => 1,
        ];
        foreach($questionArr as $question){
            $data['topics'][] = [
                'contents' => [
                    [
                        'content' => $question['sQueContent'] . ($question['iQueType'] == 1 ? '<p>答案：[答案始]'. $question['sAnswer'] . '[/答案终]</p>' : '')
                    ],
                ],
                'topicType' => 1
            ];
        }
        echo json_encode($data, JSON_UNESCAPED_UNICODE);
        $httpSender = new HttpSender();
//        $result = $httpSender->Json('http://192.168.0.149:9001/document/processing', json_encode($data, JSON_UNESCAPED_UNICODE));
        $result = $httpSender->Json('http://192.168.5.245:9000/document/processing', json_encode($data));
        var_dump($result);die;

    }*/


//    public function dealSchoolSupportAction()
//    {
//        $config = Main::getConfigByName('cBoxUrl');
//        $config or die('配置读取失败！');
//        $xml = file_get_contents($config['schoolXmlUrl']);
//        $xml or die('学校列表获取失败！');
//        $xml = simplexml_load_string($xml);
//        $xml or die('XML解析失败！');
//        $schoolArr = [];    //学校ID-名称数组
//
//        //处理xml获取学校
//        foreach($xml->children() as $school){
//            $schoolInfo = get_object_vars($school);
//            $schoolArr[] = $schoolInfo['id'];
//        }
//        $schoolArr[] = '900090009';
//        $schoolId = implode(',', $schoolArr);
//        $result = $this->db->query("update XHSchool_Info set bSupport = 1 where iSchoolId in ({$schoolId})");
//        echo $result ? '成功！' : '失败！';
//    }
//
//    public function dealBoxSchoolInfoAction()
//    {
//        $boxHisInfo = Main::getConfigByName('cBoxInfo', true);
//        $boxHisInfo = $boxHisInfo['boxHisInfo'];
//        foreach($boxHisInfo as $key => $value){
//            if($value['iSchoolId'] == 900090009){
//                unset($boxHisInfo[$key]);
//            }
//        }
//        $boxHisInfo = array_values($boxHisInfo);
//        echo XhsysConfig::createArrRecord('cBoxInfo', 'boxHisInfo', $boxHisInfo);
//    }

//    public function dealSchoolAdminPowerAction()
//    {
//        $adminUsers = $this->modelsManager->createBuilder()
//            ->columns(['iUserId', 'iSchoolId', 'sUserName', 'sLogonName'])
//            ->from('XhsysUser')
//            ->where('sLogonName like "%admin"')
//            ->getQuery()
//            ->execute();
//        foreach($adminUsers as $admin){
//            if($admin->sLogonName == 'admin') continue;
//            $power = ['id' => $admin->iSchoolId];
//            if(XhsysUserpowerNew::createExtraRecord($admin->iUserId, 'school', $power, $power)) {
//                echo $admin->sUserName, "({$admin->iUserId})学校管理权限增加成功！", json_encode($power), '<br />';
//            }
//            else{
//                echo $admin->sUserName, "({$admin->iUserId})学校管理权限增加失败！", json_encode($power), '<br />';
//            }
//            if(XhsysUserpowerNew::createRecord($admin->iUserId, '121')){
//                echo $admin->sUserName, "({$admin->iUserId})统计查看权限增加成功！", '<br />';
//            }
//            else{
//                echo $admin->sUserName, "({$admin->iUserId})统计查看权限增加失败！", '<br />';
//            }
//        }
//        echo '执行完毕！';
//        die;
//    }

//
//    public function hideBoxInfoConfigAction()
//    {
//        $result = $this->db->query('UPDATE XHSys_Config SET sSortName = "hidden" where sConfigName = "cBoxInfo"');
//        var_dump($result);
//    }
//
//    public function dealBoxInfoAction()
//    {
//        $boxInfo = Main::getConfigByName('cBoxInfo', true);
//        $schoolId = $boxInfo['schoolId'];
//        $schoolId = array_unique($schoolId);
//        $boxHisInfo = $boxInfo['boxHisInfo'];
//        $hisSchoolId = array_column($boxHisInfo, 'iSchoolId');
//        $diffSchoolId = array_diff($schoolId, $hisSchoolId);
//        $boxHisInfo = array_column($boxHisInfo, null, 'iSchoolId');
//        foreach($diffSchoolId as $id){
//            $boxHisInfo[$id] = [
//                'iSchoolId'     => $id,
//                'sBoxIp'        => '',
//                'sBoxWIp'       => '',
//                'sBoxVersion'   => '',
//                'sStartTime'    => '',
//            ];
//        }
//        XhsysConfig::createArrRecord('cBoxInfo', 'boxHisInfo', array_values($boxHisInfo));
//    }


    /**
     * #方法说明：权限写入新数据库接口
     * @param array $list ['sNodeNames'] 父节点数组
     * @param integer $list ['delete'] = 0 如果新表中有父节点不存在，则从旧表同步更新不存在的父节点自身及所有子节点的权限。如果新表父节点都存在，则提示无需同步权限。
     * @param integer $list ['delete'] = 1 如果新表中有父节点存在，则先删除新表存在的父节点自身及所有子节点的权限，然后从旧表同步更新。如果新表中父节点不存在，则直接从旧表同步更新。
     * @param array $list ['XHSys_Tree'] XHSys_Tree旧表数据
     * @param array $list ['XHSys_Power'] XHSys_Power旧表数据
     * @param array $list ['XHSys_Function'] XHSys_Function旧表数据
     * @param array $data ['XHSys_Tree'] XHSys_Tree新表数据
     * # Created by wy
     */
    public function writeNewAction()
    {
        $request = $this->request;
        if (!$request->isPost()) return $this->sendErrorResponse(500, '请求方式不正确！');
        $list = $request->getJsonRawBody(true);
        if (!$list['sNodeNames']) return $this->sendErrorResponse(400, '父节点不能为空！');
        try {
            $NewName = $iParentNodeName = array();
            $data = $this->read($list['sNodeNames'], array(0));//不读取软删除
            if (!$data) {
                $res = $this->write($list);
            } else {
                if ((int)$list['delete'] === 1) {
                    $res = $this->write($list);
                } else {
                    foreach ($data['XHSys_Tree'] as $value) {
                        if ((int)$value['iParentNodeId'] === 0) {
                            $iParentNodeName[] = $value['sNodeName'];
                        }
                    }
                    foreach ($list['sNodeNames'] as $value) {
                        if (!in_array($value, $iParentNodeName)) {
                            $NewName[] = $value;
                        }
                    }
                    if (!$NewName) {
                        return $this->sendSuccessResponse('无需同步权限！');
                    } else {
                        return $this->sendJsonResponse(array('sNodeNames' => $NewName));
                    }
                }
            }
            if (!$res) return $this->sendErrorResponse(400, '同步权限失败！');
            return $this->sendSuccessResponse('同步权限成功！');
        } catch (\Exception $e) {
            return $this->sendErrorResponse(500, $e->getMessage());
        }
    }

    /**
     * #方法说明：写入新表方法
     * @param array $list ['sNodeNames'] 父节点数组
     * @param integer $list ['delete'] = 0 如果新表中有父节点不存在，则从旧表同步更新不存在的父节点自身及所有子节点的权限。如果新表父节点都存在，则提示无需同步权限。
     * @param integer $list ['delete'] = 1 如果新表中有父节点存在，则先删除新表存在的父节点自身及所有子节点的权限，然后从旧表同步更新。如果新表中父节点不存在，则直接从旧表同步更新。
     * @param array $list ['XHSys_Tree'] XHSys_Tree表数据
     * @param array $list ['XHSys_Power'] XHSys_Power表数据
     * @param array $list ['XHSys_Function'] XHSys_Function表数据
     * @param array $data ['XHSys_Tree'] XHSys_Tree新表数据
     * # Created by wy
     */
    public function write($list)
    {
        if ((int)$list['delete'] === 1) {
            $data = $this->read($list['sNodeNames'], array(0, 1));//读取软删除
            $iNodeId = array();
            if (!empty($data)) {
                foreach ($data['XHSys_Tree'] as $value) {
                    $iNodeId[] = $value['iNodeId'];
                }
                $this->db->begin();
                if (XhsysTree::find(
                        array(
                            'iNodeId IN ({letter:array})',
                            'bind' => array(
                                'letter' => $iNodeId
                            )
                        )
                    )->delete() === false
                ) {
                    $this->db->rollback();
                    return false;
                }
                if (XhsysPower::find(
                        array(
                            'iNodeId IN ({letter:array})',
                            'bind' => array(
                                'letter' => $iNodeId
                            )
                        )
                    )->delete() === false
                ) {
                    $this->db->rollback();
                    return false;
                }
                if (XhsysFunction::find(
                        array(
                            'iNodeId IN ({letter:array})',
                            'bind' => array(
                                'letter' => $iNodeId
                            )
                        )
                    )->delete() === false
                ) {
                    $this->db->rollback();
                    return false;
                }
                $this->db->commit();
            }
        }
        unset($list['delete']);
        unset($list['sNodeNames']);
        if (!empty($list)) {
            $this->db->begin();
            $iParentNodeId = array();
            foreach ($list['XHSys_Tree'] as $value) {
                $sNodeName = array();
                $XHSysTreeNew = new XhsysTree;
                $sNodeName[] = $XHSysTreeNew->sNodeName = $value['sNodeName'];
                $XHSysTreeNew->sNodeShortName = $value['sNodeShortName'];
                $XHSysTreeNew->sNodeIcon = $value['sNodeIcon'];
                $XHSysTreeNew->iParentNodeId = in_array($value['iParentNodeId'], array_keys($iParentNodeId)) ? $iParentNodeId[$value['iParentNodeId']] : $value['iParentNodeId'];
                $XHSysTreeNew->iNodeType = $value['iNodeType'];
                $XHSysTreeNew->bDelete = $value['bDelete'];
                $XHSysTreeNew->tCreateDate = $value['tCreateDate'];
                $XHSysTreeNew->iCreateUserId = $value['iCreateUserId'];
                $XHSysTreeNew->tLastModifyDate = $value['tLastModifyDate'];
                $XHSysTreeNew->iLastModifyUserId = $value['iLastModifyUserId'];
                if ($XHSysTreeNew->save() === false) {
                    $this->db->rollback();
                    return false;
                }
                $resTree = XhsysTree::find(
                    array(
                        'sNodeName IN ({letter:array})',
                        'bind' => array(
                            'letter' => $sNodeName
                        )
                    )
                );
                foreach ($resTree as $v) {
                    $iParentNodeId[$value['iNodeId']] = $v->iNodeId;
                }
            }
            foreach ($list['XHSys_Power'] as $value) {
                $XHSysPowerNew = new XhsysPower;
                $XHSysPowerNew->iNodeId = in_array($value['iNodeId'], array_keys($iParentNodeId)) ? $iParentNodeId[$value['iNodeId']] : $value['iNodeId'];
                $XHSysPowerNew->sPowerTag = $value['sPowerTag'];
                $XHSysPowerNew->bPowerMain = $value['bPowerMain'];
                $XHSysPowerNew->sPowerName = $value['sPowerName'];
//                $XHSysPowerNew->bPowerExtra = $value['bPowerExtra'];
                $XHSysPowerNew->sExtraUrl = $value['sExtraUrl'];
                if ($XHSysPowerNew->save() === false) {
                    $this->db->rollback();
                    return false;
                }
            }
            foreach ($list['XHSys_Function'] as $value) {
                $XHSysFunctionNew = new XhsysFunction;
                $XHSysFunctionNew->iNodeId = in_array($value['iNodeId'], array_keys($iParentNodeId)) ? $iParentNodeId[$value['iNodeId']] : $value['iNodeId'];
                $XHSysFunctionNew->sFunctionName = $value['sFunctionName'];
                $XHSysFunctionNew->sFunctionUrl = $value['sFunctionUrl'];
                $XHSysFunctionNew->sFunctionAttr = $value['sFunctionAttr'];
                $XHSysFunctionNew->bDelete = $value['bDelete'];
                $XHSysFunctionNew->tCreateDate = $value['tCreateDate'];
                $XHSysFunctionNew->iCreateUserId = $value['iCreateUserId'];
                $XHSysFunctionNew->tLastModifyDate = $value['tLastModifyDate'];
                $XHSysFunctionNew->iLastModifyUserId = $value['iLastModifyUserId'];
                if ($XHSysFunctionNew->save() === false) {
                    $this->db->rollback();
                    return false;
                }
            }
            $this->db->commit();
        }
        return true;
    }

    /**
     * #方法说明：根据指定父节点数组，读取新数据库
     * @param array $sNodeNames 父节点数组
     * @param array $bDelete 判断是否读取软删除
     * # Created by wy
     */
    public function read($sNodeNames, $bDelete)
    {
        $resTree = XhsysTree::find(
            array(
                'bDelete IN ({letter:array})',
                'bind' => array(
                    'letter' => $bDelete
                ),
            )
        );
        $getTree = $this->getTree($resTree, $sNodeNames);
        $data = $iNodeId = array();
        if (!empty($getTree)) {
            $data['XHSys_Tree'] = $this->formatTree($getTree, 1);
            foreach ($data['XHSys_Tree'] as $value) {
                $iNodeId[] = $value['iNodeId'];
            }
            $resPower = XhsysPower::find(
                array(
                    'iNodeId IN ({letter:array})',
                    'bind' => array(
                        'letter' => $iNodeId
                    )
                )
            );
            $data['XHSys_Power'] = $this->getPower($resPower);
            $resFunction = XhsysFunction::find(
                array(
                    'iNodeId IN ({letter:array})',
                    'bind' => array(
                        'letter' => $iNodeId
                    )
                )
            );
            $data['XHSys_Function'] = $this->getFunction($resFunction);
        }
        return $data;
    }

    /**
     * #方法说明：分类获取并筛选方法
     * @param array $sNodeNames 父节点数组
     * # Created by wy
     */
    public function getTree($data, $sNodeNames)
    {
        $items = $access = $list = array();
        if (!empty($data)) {
            foreach ($data as $value) {
                $items[$value->iNodeId] = array(
                    'iNodeId' => $value->iNodeId,
                    'sNodeName' => $value->sNodeName,
                    'sNodeShortName' => $value->sNodeShortName,
                    'sNodeIcon' => $value->sNodeIcon,
                    'iParentNodeId' => $value->iParentNodeId,
                    'iNodeType' => $value->iNodeType,
                    'bDelete' => $value->bDelete,
                    'tCreateDate' => $value->tCreateDate,
                    'iCreateUserId' => $value->iCreateUserId,
                    'tLastModifyDate' => $value->tLastModifyDate,
                    'iLastModifyUserId' => $value->iLastModifyUserId,
                );
            }
            foreach ($items as $key => $item) {
                if ((int)$item['iParentNodeId'] === 0) {
                    $access[] = &$items[$key];
                } else {
                    $items[$item['iParentNodeId']]['son'][] = &$items[$key];
                }
            }
            foreach ($access as $acc) {
                if (in_array($acc['sNodeName'], $sNodeNames)) {
                    $list[] = $acc;
                }
            }
        }
        return $list;
    }

    /**
     * #方法说明：分类递归格式化方法
     * @param integer $iscache 判断是否需要清空
     * # Created by wy
     */
    public function formatTree($data, $delete = 0)
    {
        static $list = array();
        if ($delete === 1)
            $list = array();
        foreach ($data as $value) {
            if (array_key_exists('son', $value)) {
                $son = array_pop($value);
                $list[] = $value;
                $this->formatTree($son);
            } else {
                $list[] = $value;
            }
        }
        return $list;
    }

    /**
     * #方法说明：权限获取方法
     * # Created by wy
     */
    public function getPower($data)
    {
        $list = array();
        foreach ($data as $value) {
            $list[] = array(
                'iPowerId' => $value->iPowerId,
                'iNodeId' => $value->iNodeId,
                'sPowerTag' => $value->sPowerTag,
                'bPowerMain' => $value->bPowerMain,
                'sPowerName' => $value->sPowerName,
//                'bPowerExtra' => $value->bPowerExtra,
                'sExtraUrl' => $value->sExtraUrl,
            );
        }
        return $list;
    }

    /**
     * #方法说明：路径获取方法
     * # Created by wy
     */
    public function getFunction($data)
    {
        $list = array();
        foreach ($data as $value) {
            $list[] = array(
                'iFunctionId' => $value->iFunctionId,
                'iNodeId' => $value->iNodeId,
                'sFunctionName' => $value->sFunctionName,
                'sFunctionUrl' => $value->sFunctionUrl,
                'sFunctionAttr' => $value->sFunctionAttr,
                'bDelete' => $value->bDelete,
                'tCreateDate' => $value->tCreateDate,
                'iCreateUserId' => $value->iCreateUserId,
                'tLastModifyDate' => $value->tLastModifyDate,
                'iLastModifyUserId' => $value->iLastModifyUserId,
            );
        }
        return $list;
    }

    /**
     * @param int $code
     * @param string $msg
     * @param string $description
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20170814
     *
     * @SWG\Response(response="Error", description="错误", @SWG\Schema(ref="#/definitions/Error")),
     */
//    public function sendErrorResponse($code = 200, $msg = '未知错误！', $description = '')
//    {
//        return $this->response->setStatusCode($code)
//            ->setJsonContent(['code' => $code, 'msg' => $msg, 'description' => $description], JSON_UNESCAPED_UNICODE);
//    }

    /**
     * function explain
     *
     * @param string $msg
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20170814
     *
     * @SWG\Response(response="Success", description="成功", @SWG\Schema(ref="#/definitions/Success")),
     */
//    public function sendSuccessResponse($msg = '执行成功！')
//    {
//        return $this->response->setJsonContent(['code' => 200, 'msg' => $msg], JSON_UNESCAPED_UNICODE);
//    }
//
//    public function sendJsonResponse($array = array())
//    {
//        return $this->response->setJsonContent($array, JSON_UNESCAPED_UNICODE);
//    }

//    public function schoolTransformAction()
//    {
//        if (!User::isAdmin() && strtolower(Main::getLoginUserInfo('logonName')) != 'aichenk') {
//            die("无操作权限！");
//        }
//        $this->view->setVar('Ver', '?ver=' . VER);
//        if (!$this->request->isPost()) {
//            return $this->flash->success('选择文件并输入学校id');
//        }
//        if ($this->request->getPost('exec', 'string')) {
//            goto exec;
//        }
//        $schoolId = $this->request->getPost('schoolId', 'int');
//        $file     = $this->request->getUploadedFiles()[0];
//        if (!$schoolId || !$file) {
//            return $this->flash->error('缺少参数！');
//        }
//        try {
//            $fileName = $file->getName();
//            if (Tool::isWindows()) {
//                $fileName = iconv('utf-8', 'GBK', $fileName);
//            }
//            $filePath = Tool::buildPath(TEMP_PATH, $fileName);
//            $file->moveTo($filePath);
//
//            //获取用户账号
//            $account = self::readAccountForSchoolTransform($filePath);
//            @unlink($filePath);
//            if (!$account) {
//                return $this->flash->error('账号为空');
//            }
//            $accountStr = '\'' . implode('\',\'', $account) . '\'';
//
//            //查找用户id
//            $users = $this->db->fetchAll("select iUserId from XHSys_User where sLogonName in ({$accountStr})");
//            $userIds = array_column($users, 'iUserId');
//            $userIdStr = implode(',', $userIds);
//
//            $count = [
//                'source' => count($account),
//                'real' => count($userIds)
//            ];
//            $oldCenterDB = new Mysql(Main::getConfigByName('oldCenterDB'));
//            $oldName = APP_DEV ? 'xh_zjhzztxx_school' : 'xh_product';
//
//            $oldDBName = $newDBName = '';
//            $oldSchoolId = $oldCenterDB->fetchOne("select us_school_xxid from {$oldName}.users where us_id in ({$userIdStr})")['us_school_xxid'];
//            Main::getSchoolMainDB($oldSchoolId, $oldDBName);
//            Main::getSchoolMainDB($schoolId, $newDBName);
//
//            $sqlResult = [
//                'newCenter' => "update xh_webmanage.XHSys_User set iSchoolId = '{$schoolId}' where iUserId in ({$userIdStr})",
//                'oldCenter' => "update {$oldName}.users set us_school_xxid = '{$schoolId}' where us_id in ({$userIdStr})",
//                'oldSchool' => "update {$oldDBName}.users set us_school_xxid = '{$schoolId}',us_state = 2 where us_id in ({$userIdStr})",
//            ];
////            $this->db->query('set names \'latin1\'');
//            $userInfo =$oldCenterDB->fetchAll("select * from {$oldName}.users where us_id in ({$userIdStr})");
//
//            $fields = $data = [];
//            foreach ($userInfo[0] as $key => $value) {
//                $fields[] = $key;
//            }
//            foreach ($userInfo as $user) {
//                $user['us_school_xxid'] = $schoolId;
//                $data[] = '(\'' . implode('\',\'', $user) . '\')';
//            }
//            $sqlResult['newSchool'] = "insert into {$newDBName}.users (" . implode(',', $fields) . ") values " . implode(',', $data);
//            $this->flash->notice('请检查语句是否正确');
//            return $this->view->setVars([
//                'count'     => $count,
//                'sqlResult' => $sqlResult,
//                'school'    => ['old' => $oldSchoolId, 'new' => $schoolId]
//            ]);
//        }
//        catch (\Exception $e) {
//            return $this->flash->error($e->getMessage());
//        }
//
//        exec:
//        try{
//            $oldSchoolId = $this->request->getPost('oldSchoolId', 'int');
//            $newSchoolId = $this->request->getPost('newSchoolId', 'int');
//            $request = $this->request->getPost();
//            $oldDBName = $newDBName = '';
//            $oldDB = Main::getSchoolMainDB($oldSchoolId, $oldDBName);
//            $newDB = Main::getSchoolMainDB($newSchoolId, $newDBName);
//            $oldCenterDB = new Mysql(Main::getConfigByName('oldCenterDB'));
//            $result = [];
//            $result['newCenter'] = $this->db->execute($request['newCenter']);
//            $result['oldCenter'] = $oldCenterDB->execute($request['oldCenter']);
//            $result['oldSchool'] = $oldDB->execute($request['oldSchool']);
//            $result['newSchool'] = $newDB->execute($request['newSchool']);
//            return $this->view->setVars([
//                'result' => $result
//            ]);
//        }
//        catch (\Exception $e) {
//            return $this->flash->error($e->getMessage());
//        }
//    }
//
//    private static function readAccountForSchoolTransform($fileName)
//    {
//        require_once APP_PATH . '/common/library/PHPExcel/PHPExcel.php';
//        require_once APP_PATH . '/common/library/PHPExcel/PHPExcel/IOFactory.php';
//        try {
//            switch (strtolower(pathinfo($fileName)['extension'])) {
//                case 'xls':
//                    $excel = (new \PHPExcel_Reader_Excel5())->load($fileName);
//                    break;
//                case 'xlsx':
//                    $excel = (new \PHPExcel_Reader_Excel2007())->load($fileName);
//                    break;
//                case 'csv':
//                    $excel = (new \PHPExcel_Reader_CSV())->load($fileName);
//                    break;
//                default:
//                    throw new \Exception('暂不支持该文件类型！');
//            }
//            $account = [];
//            for ($i = 0; $i < $excel->getSheetCount(); $i++) {
//                $sheet      = $excel->getSheet($i);
//                $rowNum     = $sheet->getHighestRow();
//                for ($row = 2; $row <= $rowNum; $row++) {
//                    $account[] = $sheet->getCellByColumnAndRow(0, $row)->getValue();
//                }
//            }
//            return array_values(array_filter($account));
//        }
//        catch (\Exception $e){
//            throw new \Exception($e->getMessage());
//        }
//    }

	/**
	 * 【脚本】检测学校区域不同
	 *
	 * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
	 *
	 * create by qgz 20180813
	 */
    public function checkAreaDataAction(){
	    $data = $this->db->fetchAll("select iSchoolId, sProvinceName,sCityName,sCountyName from XHSchool_Info where bDelete = 0");
	    try {
		    $areaData = new Area();
		    $areaData = $areaData->getAllCodes();
		    foreach ($data as $value){
		    	$exist = false;
			    if ($value['sProvinceName']){
			    	if (!in_array($value['sProvinceName'],$areaData)){
			    		$value['type'][] = '省';
					    $exist = true;
				    }
			    }
			    if ($value['sCityName']){
				    if (!in_array($value['sCityName'],$areaData)){
					    $value['type'][] = '市';
					    $exist = true;
				    }
			    }
			    if ($value['sCountyName']){
				    if (!in_array($value['sCountyName'],$areaData)){
					    $value['type'][] = '区';
					    $exist = true;
				    }
			    }
			    if ($exist){
			    	$msg = '学校id：' . $value['iSchoolId'] . '；' . '地区：' . $value['sProvinceName'].'-'.$value['sCityName'].'-'.$value['sCountyName'] . '；不同：' . implode(',', $value['type'])."<br/>";
				    echo $msg;
			    }
		    }
	    } catch ( \Exception $e ) {
		    return $this->sendErrorResponse( 500, $e->getMessage() );
	    }
    }

    /**
     * 脚本检测设备维修延时,凌晨后每天一次
     *
     *
     * create by qgz 20180917
     */
    public function runRepairDelayDataAction()
    {
        $allDelayData = XhsysDevicerepairDelay::find(['conditions' => 'bDelete = 0']);
        if (!$allDelayData) {
            echo 'No data need check.';die;
        }
        $delayNum = $applyNum = 0;
        foreach ($allDelayData as $delayData){
            if ($delayData->iFinishStatus == 0) {//只检测没完成的
                if ($delayData->tEndDate) {
                    if (date('Y-m-d') > $delayData->tEndDate) {//如果延期
                        $delayData->iDelayStatus = 1;
                        if (!$delayData->save()) {
                            $this->sendErrorResponse(500, '修改延时状态出错，状态id:' . $delayData->iId);
                        }
                        $delayNum++;
                        $repairApplyData = XhsysDevicerepair::findFirst([
                            'conditions' => 'bDelete = 0 and iId = :iId:',
                            'bind' => ['iId' => $delayData->iRepairApplyId]
                        ]);
                        $delayRepairStatus = $this->delayRepairStatus[$delayData->iProgressStatus];
                        if (in_array($repairApplyData->iStatus, $delayRepairStatus)) {//申请表需要记录当前状态是否延时
                            $repairApplyData->iDelayStatus = $delayData->iProgressStatus;
                            if (!$repairApplyData->save()) {
                                $msg = '延时id:' . $delayData->iId . '和维修id :' . $repairApplyData->iId . '出现了错误。';
                                $this->sendErrorResponse(500, $msg);
                            }
                            $applyNum++;
                        }
                    }
                }
            }
        }
        return $this->sendSuccessResponse('修改延时数据:' . $delayNum . '，修改维修数据:' . $applyNum);
    }

    /**
     * 脚本，教辅申请刷新发布状态，可接受参数，凌晨后每天一次
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by qgz 20180920
     */
    public function refreshPublishStatusAction()
    {
        $data = XhresReferenceApply::find([
            'conditions' => " bDelete = 0 and iBookId != '' and iBookId IS NOT NULL "
        ]);

        if ($data) {
            foreach ($data as $value) {
                if ($value->iBookId) {
                    $books = new Books();
                    $result = $books->getBookDetail($value->iBookId);
                    if ($result && $result['bookId'] == $value->iBookId) {
                        if ($value->iPublishStatus != 5) {//5已发布，不刷新
                            $value->iPublishStatus = $result['publishStatus'];
                        }
                        $value->iCompleteStatus = $result['bookComplete'];
                        $value->iBookType = $result['bookType'];//出版社，加上先，以后保存申请时有就可去掉
                        if (!$value->save(null, null, true)) {
                            $this->sendErrorResponse(
                                500,
                                '更新书出错,书id:' . $value->iBookId .',编号id:' . $value->iId
                            );
                        }
                    }
                }
            }
            return $this->sendSuccessResponse('刷新数据成功');
        } else {
            return $this->sendSuccessResponse('成功，没有需要刷新的数据');
        }
    }

    /**
     * 脚本检测教辅排期延时情况，每天凌晨后跑一次
     *
     *
     * create by qgz 20180921
     */
    public function runReferenceApplyPlanDateAction()
    {
        $checkHours = 12;
        $data = XhresReferencePlan::find([
            'conditions' => ' bDelete = 0 and iStatus = 0 '
        ]);
        if ($data) {
            foreach ($data as $value) {
                if (!$value->sNoteDate) {
                    continue;
                }
                $checkDate = date("Y-m-d H:i:s", strtotime("+" . $checkHours . " hours", strtotime($value->sNoteDate)));
                if (date('Y-m-d H:i:s') > $checkDate) {
                    $value->iStatus = 1;
                    if (!$value->save(null, null, true)) {
                        $this->sendErrorResponse(500, '检测数据出错，id:' . $value->iId . PHP_EOL);
                    }
                } else {
                    continue;
                }
            }
            return $this->sendSuccessResponse('检测完成');
        } else {
            return $this->sendSuccessResponse('没有数据需要检测');
        }

    }

    public function faqUpdateAction()
    {
        $parame = [
            'conditions' => 'bDelete = 0',
        ];
        $result  = Main::runModelPage('\\Admin\\Models\\faq\\XhfaqInfo', $parame);
        foreach ($result['rows'] as $key => $value) {
            if (!$value['iClassifyId']) {
                $iAppCode = $value['iAppCode'];
                if ($iAppCode) {
                    $params['conditions'] = 'bDelete = 0 AND sTag = :sTag: AND iType = 1';
                    $params['bind'] = ['sTag' => $value['iAppCode']];
                    $sAppName = XhsysClassification::findFirst($params);
                    if (!$sAppName) {
                        // 根据iAppCode 找到对应的sAppName
                        $builder['columns'] = 'sEnumName';
                        $builder['conditions'] = "sEnumValue = :sEnumValue:";
                        $builder['bind'] = ['sEnumValue' => $iAppCode];
                        $result = XhsysEnum::findFirst($builder);
                        if ($result) {
                            $params['conditions'] = "sTag = :sTag:";
                            $params['bind'] = ['sTag' => $iAppCode];
                            $stag = XhsysClassification::findFirst($params);
                            if (!$stag) {
                                // 新增分类信息
                                $object = new XhsysClassification();
                                $data['sName'] = $result->sEnumName;
                                $data['sTag'] = $iAppCode;
                                $data['iType'] = 1;
                                $data['iParentId'] = 0;
                                $object->assign($data);
                                $results = $object->save();
                                if (!$results) {
                                    return $this->sendErrorResponse(400, '添加分类失败');
                                }
                            }
                        }
                    }
                    // 通过iAppCode找到id 更新到XHFaq_Info中的 iClassifyId， iMainClassifyId
                    $parameters = [
                        'columns' => 'id',
                        'conditions' => 'bDelete = 0 AND sTag = :sTag:',
                        'bind' => ['sTag' => $iAppCode]
                    ];
                    $id = XhsysClassification::findFirst($parameters);
                    if ($id) {
                        $realData['iClassifyId'] = $id->id;
                        $realData['iMainClassifyId'] = FaqController::getParentId($realData['iClassifyId']);
                        if ($value['iFAQId']) {
                            $faq = XhfaqInfo::findFirst($value['iFAQId']);
                            $faq->assign($realData);
                            if (!$faq -> save()) {
                                return $this->sendErrorResponse(400, '数据更新失败');
                            }
                        }
                    }
                }
            }
        }
        return $this->sendSuccessResponse('数据更新成功');
    }

    /**
     * 修复排期书年级、完成未完成数据（一次）
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by qgz 20181016
     */
    public function runBookClassDataAction()
    {
        $XhresReferenceApply = XhresReferenceApply::find([
            'conditions' => " bDelete = 0 and iBookId != '' and iBookId is not null "
        ]);
        if (!$XhresReferenceApply){
            return $this->sendSuccessResponse('没有需要更新的数据');
        }
//        $bookArr = [];
        foreach ($XhresReferenceApply as $value) {
            if ($value->iBookId && (!$value->iBookClass || !$value->iCompleteStatus)) {
                //增加年级信息
                $books = new Books();
                $result = $books->getBookDetail(trim($value->iBookId));
                if ($result && $result['bookId'] == trim($value->iBookId)) {
                    $value->iBookClass = $result['gradeId'];
                    $value->iCompleteStatus = $result['bookComplete'];
                    if (!$value->save(null, null, true)) {
                        $this->sendErrorResponse(
                            500,
                            '更新书年级数据出错,书id:' . $value->iBookId .',编号id:' . $value->iId
                        );
                    }
                }
//                $bookArr[$value->iBookId] = $value->sBookName;
            }
        }

//        $XhresReferencePlan = XhresReferencePlan::find([
//            'conditions' => ' bDelete = 0 '
//        ]);
//        foreach ($XhresReferencePlan as $item) {
//            $item->sBookName = isset($bookArr[$item->iBookId]) ? $bookArr[$item->iBookId] : '';
//            if (!$item->save()) {
//                $this->sendErrorResponse(
//                    500,
//                    '更新排期书名出错,书id:' . $item->iBookId .',编号id:' . $item->iId
//                );
//            }
//        }
        return $this->sendSuccessResponse('数据更新成功');
    }

    public function runNameAction()//一次
    {
        $XhresReferencePlan = XhresReferencePlan::find([
            'conditions' => ' bDelete = 0 '
        ]);
        foreach ($XhresReferencePlan as $value) {
            if ($value->iBookId && !$value->sBookName) {
                //增加学科版本信息
                $books = new Books();
                $result = $books->getBookDetail(trim($value->iBookId));
                if ($result && $result['bookId'] == trim($value->iBookId)) {
                    $value->sBookName = $result['bookName'];
                    if (!$value->save(null, null, true)) {
                        $this->sendErrorResponse(
                            500,
                            '更新书科目数据出错,书id:' . $value->iBookId .',编号id:' . $value->iId
                        );
                    }
                }
            }
        }
        return $this->sendSuccessResponse('数据更新成功');
    }

    /**
     * 更新教辅列表是否有排期计划, 1有排期计划2新申请3已过期
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by qgz 20181016
     */
//    public function runIsExistPlanDataAction()
//    {
//        $XhresReferencePlan = XhresReferencePlan::find([
//            'conditions' => 'bDelete = 0'
//        ]);
//        $idArr = [];
//        foreach ($XhresReferencePlan as $value) {
//            if (isset($idArr[trim($value->iBookId)])) {
//                if ($idArr[trim($value->iBookId)] == 1) {
//                    continue;//存在计划
//                }
//                if ($idArr[trim($value->iBookId)] == 3 || $idArr[trim($value->iBookId)] == 2) {
//                    if ($value->sRealEndDate) {
//                        $idArr[trim($value->iBookId)] = 1;//存在计划
//                    } else {
//                        if (date('Y-m-d', time()) > $value->sEndDate) {
//                            $idArr[trim($value->iBookId)] = 3;//过期
//                        } else {
//                            $idArr[trim($value->iBookId)] = 2;//新申请
//                        }
//                    }
//                }
//            } else {
//                if ($value->sRealEndDate) {
//                    $idArr[trim($value->iBookId)] = 1;//存在计划
//                } else {
//                    if (date('Y-m-d', time()) > $value->sEndDate) {
//                        $idArr[trim($value->iBookId)] = 3;//过期
//                    } else {
//                        $idArr[trim($value->iBookId)] = 2;//新申请
//                    }
//                }
//            }
//        }
//        $pro = XhresReferenceApply::find([
//            'conditions' => " bDelete = 0 and iBookId is not null and iBookId != '' "
//        ]);
//        foreach ($pro as $item) {
//            if ($item->iBookId && isset($idArr[$item->iBookId])) {
//                $item->iExistPlan = $idArr[$item->iBookId];
//                if (!$item->save(null, null, true)) {
//                    $this->sendErrorResponse(
//                        500,
//                        '更新存在计划出错,书id:' . $item->iBookId .',编号id:' . $item->iId
//                    );
//                }
//            }
//        }
//        return $this->sendSuccessResponse('数据更新成功');
//    }

    /**
     * 排期计划-给相关的人在[计划完成时间]前一天发短信
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by qgz 20181016
     */
    public function checkPlanSendMsgAction()
    {
        $sendMsgArr = [];
        $nextDay = date('Y-m-d', strtotime("+1 day"));
        $proData = XhresReferencePlan::find([
            'conditions' => " bDelete = 0 and (iAddType = 1 or iAddType = 2) and sRealEndDate = :sRealEndDate: ",
            'bind' => ['sRealEndDate' => $nextDay]
        ]);
        if (!$proData) {
            return $this->sendSuccessResponse('没有需要更新的数据');
        }
        foreach ($proData as $value) {
            if ($value->iAddType == 2) {
                $applyData = XhresReferenceApply::findFirst([
                    'conditions' => 'bDelete = 0 and iId = :iId:',
                    'bind' => ['iId' => $value->iApplyId]
                ]);
                $sendUser = $applyData->iCreateUserId;
            } else {
                $sendUser = $value->iCreateUserId;
            }
            $sendMsgArr[] = [
                'createUser' => $sendUser,
                'bookId' => $value->iBookId,
                'bookName' => $value->sBookName,
                'realStartDate' => $value->sRealStartDate,
                'realEndDate' => $value->sRealEndDate,
                'sDemand' => $value->sDemand
            ];
        }
        if ($sendMsgArr) {//给相关人发短信
            $this->sendPlanMsg($sendMsgArr);
        }
        return $this->sendSuccessResponse('成功');
    }

    /**
     * 排期计划-给相关的人发短信
     *
     * @param $data
     *
     * @return bool
     *
     * create by qgz 20181016
     */
    public function sendPlanMsg($data)
    {
        if (empty($data)) {
            return true;
        }
        $user = $book = [];
        foreach ($data as $value) {
            if (isset($value['createUser']) && isset($value['bookId']) && $value['createUser'] && $value['bookId']) {
                $user[$value['createUser']][$value['bookId']][] = $value;
                $book[$value['bookId']] = $value['bookName'];
            }
        }
        $catalogArr = $showCatalogArr = [];
        $result['catalogs'] = [];
        $userArr = array_keys($user);
        if (!$userArr) {
            return true;
        }
        $userStaffInfo = XhhrmStaff::find([
            'columns' => 'iUserId, sSelfPhone',
            'conditions' => 'bDelete = 0 and iUserId IN ({idArr:array})',
            'bind' => ['idArr' => $userArr]
        ])->toArray();
        if (!$userStaffInfo) {
            $this->createCommitLog('没有人员id', '部门表中找不到人员信息');
            return true;
        }
        $phoneNumArr = array_column($userStaffInfo, 'sSelfPhone', 'iUserId');
        if (!$phoneNumArr) {
            return true;
        }
        foreach ($user as $userId => $dataValue) {
            $msg = '教辅申请排期计划时间即将到期；';
            foreach ($dataValue as $bookId => $dateTime) {
                try {
                    $params = [
                        'textBookVersion' => 1,
                        'gradeId' => 1,
                        'subjectId' => 1
                    ];//这三个参数传任意非空数据即可
                    $books = new Books();
                    $result = $books->getCatalogsByBookId($bookId, $params);//获取书章节数据
                    if (isset($result['catalogs']) && $result['catalogs']) {
                        foreach ($result['catalogs'] as $value) {
                            $catalogArr[$value['catalogId']] = $value['catalogName'];//列表中展示的章节
                        }
                    }
                } catch (\Exception $e) {
                    $this->createCommitLog('获取章节信息接口出错', '错误信息：' . $e->getMessage());
                    return true;
                }
                $msg .= '书名：' . (isset($book[$bookId]) ? $book[$bookId] : '未知') . '；';
                foreach ($dateTime as $value) {
                    //加上章节信息
                    $demandArr = [];
                    $handDemand = explode(',', $value['sDemand']);
                    foreach ($handDemand as $item) {
                        $catalogId = ['catalogId' => $item];
                        $books = new Books();
                        $catalogInfo = $books->getCatalogsByCatalogId($catalogId);//根据章节id获取章节数据
                        if ($catalogInfo) {
                            $catalogInfo = array_column($catalogInfo, 'catalogName', 'catalogId');
                            if (isset($catalogInfo[$item]) && $catalogInfo[$item]) {
                                $demandArr[] = $catalogInfo[$item];
                            }
                        }
//                        if (isset($catalogArr[$item]) && $catalogArr[$item]) {
//                            $demandArr[] = $catalogArr[$item];
//                        }
                    }
                    if ($demandArr) {
                        $value['sDemand'] = implode('，', $demandArr);
                    }
                    if ($result['catalogs']) {
                        $res = new ResController();
                        $rootParentId = $res->handleCateLogName($result['catalogs'], $handDemand[0], 2);
                        if (!in_array($rootParentId, $handDemand)) {//加上最高层章节信息
                            $value['sDemand'] = isset($catalogArr[$rootParentId]) && $catalogArr[$rootParentId] ?
                                $catalogArr[$rootParentId] . '：' . $value['sDemand'] : $value['sDemand'];
                        }
                    }
                    $msg .= '计划时间：' . $value['realStartDate'] . '至' . $value['realEndDate'] . '、';
                    $msg .= '排期章节：' . $value['sDemand'] . '；';
                }
            }
            try {
                if (isset($phoneNumArr[$userId]) && $phoneNumArr[$userId]) {
                    Main::sendSMS($phoneNumArr[$userId], $msg);
                    $this->createCommitLog('发短信成功', '发送号码：' . $phoneNumArr[$userId] . '内容：' . $msg);
                }
            } catch (\Exception $e) {
                $this->createCommitLog('发短信出错', '错误信息：' . $e->getMessage());
                return true;
            }
        }
        return true;
    }

    /**
     * 盒子资料初始化脚本（一次）
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     * @throws XhException
     *
     * create by qgz 20181112
     */
    public function runBoxInfoAction()
    {
        $data = Box::getBox('', 0, '', '', 0, 500);
        if (!$data) {
            return $this->sendSuccessResponse('成功，没有需要转换的数据');
        }
        $do = [];
        try {
            foreach ($data as $datum) {
                if (!$datum['mac']) {
                    continue;
                }
                $findData = XhdeviceBoxInfo::findFirst([
                    'conditions' => 'bDelete = 0 and sMac = :sMac:',
                    'bind' => ['sMac' => $datum['mac']]
                ]);
                if ($findData) {//如果已经存在，不保存
                    continue;
                }
                $boxInfo = new XhdeviceBoxInfo();
                $status = Box::getBoxStatusByMac($datum['mac']);//盒子状态
                $boxInfo->sMac = $datum['mac'];
                $boxInfo->iStatus = $status == 'not fount' ? 2 : 1;//离线或在线
                $customerInfo = XhcustInfo::findFirst([
                    'columns' => 'iCUId',
                    'conditions' => 'bDelete = 0 and iSchoolId = :iSchoolId:',
                    'bind' => ['iSchoolId' => $datum['schoolId']]
                ]);
                if ($customerInfo) {
                    $boxInfo->iCUId = $customerInfo->iCUId;
                }
                if (!$boxInfo->save()) {
                    $this->sendErrorResponse(500, '保存出错，mac：'  . $datum['mac']);
                }
                $do[] = $datum['mac'];
            }
            return $this->sendSuccessResponse('成功，mac：' . implode(',' , $do));
        } catch (\Exception $e) {
            return $this->sendErrorResponse(500, $e->getMessage());
        }
    }

    /**
     * 修复XhresReferencePlan 表中新增iAddType字段数据为空
     *
     *
     * create by qgz 20181130
     */
    public function runAddTypeDataAction()
    {
        $data1 = XhresReferencePlan::find([
            'columns' => '*',
            'conditions' => " bDelete = 0 and (iAddType = '' OR iAddType IS NULL) AND (iApplyId IS NOT NULL AND iApplyId != '') AND (sStartDate is NULL OR sStartDate = '') AND (sEndDate is NULL OR sEndDate = '') AND (sRealStartDate is not NULL AND sRealStartDate != '') AND (sRealEndDate is not NULL AND sRealEndDate != '') AND tCreateDate < '2018-11-30 12:00:00' "
        ]);
        echo '处理添加类型为2，即从教辅申请--排期计划， 开始：' . '<br>';
        foreach ($data1 as $item) {
            if ($item->iId) {
                echo $item->iId . '<br>';
                $item->iAddType = 2;
                if (!$item->save(null, null, true)) {
                    echo '更新出错：iId：' . $item->iId . '<br>';
                }
            }
        }

        $data2 = XhresReferencePlan::find([
            'columns' => '*',
            'conditions' => " bDelete = 0 and (iAddType = '' OR iAddType IS NULL) AND sEndDate is NOT NULL AND sEndDate != '' AND tCreateDate < '2018-11-30 12:00:00' "
        ]);
        echo '处理添加类型为1，即直接申请， 开始：' . '<br>';
        foreach ($data2 as $item) {
            if ($item->iId) {
                echo $item->iId . '<br>';
                $item->iAddType = 1;
                if (!$item->save()) {
                    echo '更新出错：iId：' . $item->iId . '<br>';
                }
            }
        }

        $data3 = XhresReferencePlan::find([
            'columns' => '*',
            'conditions' => " bDelete = 0 AND tCreateDate < '2018-11-30 12:00:00' AND (iAddType = '' OR iAddType IS NULL) AND (iApplyId IS NULL OR iApplyId = '') AND (sEndDate is NULL OR sEndDate = '') "
        ]);
        echo '处理添加类型为3，即排期汇总（有或无id）或排期查询， 开始：' . '<br>';
        foreach ($data3 as $item) {
            if ($item->iId) {
                echo $item->iId . '<br>';
                $item->iAddType = 3;
                if (!$item->save(null, null, true)) {
                    echo '更新出错：iId：' . $item->iId . '<br>';
                }
            }
        }
        echo '结束；';
    }





//    /**
//     * 流程计划执行更新操作
//     *
//     * create by dale  20180906
//     */
//    public function transUpdateAction()
//    {
//        $applyArr = XHImsApplyTablet::find([
//            'columns'    => 'iSchoolId,sClasses,iStuNum,iTchNum,iBPPId',
//            'conditions' => 'bDelete = 0 and iState = 3 and iType = 1 and iSchoolId is not null',
//            'bind'       => [],
//        ])->toArray();
//        if (!$applyArr) {
//            echo '未查询到需要替换的数据<br>';
//        }
//        $orderArr = [];
//        foreach ($applyArr as $row) {
//            $orderArr[$row['iSchoolId']][] = $row;
//        }
//        $schoolName = School::getSchools(true);
//        foreach ($orderArr as $index => $rows) {
//            echo $schoolName[$index].'执行流转单更新操作<br>';
//            $obj = XHBpmTransList::findFirst([
//                'conditions' => 'bDelete= 0 and iBPPId = :iBPPId:',
//                'bind'       => ['iBPPId' => $rows[0]['iBPPId']]
//            ]);
//            if (!$obj) {
//                echo '未查询到需要替换的流转单,流程计划id为:'.$rows[0]['iBPPId'].'<br>';
//            }
//            $stuNum = 0;
//            $tchNum = 0;
//            $classes = [];
//            foreach ($rows as $row) {
//                $stuNum += $row['iStuNum'] ?: 0;
//                $tchNum += $row['iTchNum'] ?: 0;
//                $classArr = array_values(array_filter(explode(',', $row['sClasses'])));
//                if ($classArr) {
//                    $classes = array_merge($classes, $classArr);
//                }
//            }
//            $classes = array_values(array_filter(array_unique($classes)));
//            $obj->bUpdate = 1;
//            $obj->iStudentNum = $stuNum;
//            $obj->iTeacherNum = $tchNum;
//            $obj->iClassNum = count($classes);
//            $obj->sClasses = implode(',', $classes);
//            if (!$obj->save()) {
//                echo '流转单更新失败,流转单id为:'.$obj->iBPLId.'<br>';
//            }
//        }
//        echo '流转单更新已全部执行完毕'.'<br>';
//    }

//    /**
//     * 学生机更新流程计划id
//     *
//     * create by dale  20180912
//     */
//    public function updateStuApplyAction(){
//        $tabletArr =XHImsApplyTablet::find([
//            'conditions' => 'iType = :iType: and bDelete = 0',
//            'bind'      => ['iType' => 2]
//        ]);
//        $schoolName = School::getSchools(true);
//        foreach ($tabletArr as $tablet) {
//            if($tablet->iSchoolId) {
//                $sql = "select c.iSchoolId,p.iBPPId from XHCust_Info as c left join XHBpm_Plan as p on p.iCUId = c.iCUId
//                    where p.bFinish = 0 and p.bDelete = 0 and c.iSchoolId = {$tablet->iSchoolId} order by p.iBPPId desc LIMIT 1";
//                $plan = $this->db->fetchOne($sql);
//                if (!$plan) {
//                    echo '<font color="red">'.$schoolName[$tablet->iSchoolId].',未创建流程计划</font><br>';
//                }
//                if ($plan && isset($plan['iBPPId'])) {
//                    $res = $this->db->execute("update XHIms_ApplyTablet set iBPPId = {$plan['iBPPId']}  where iRTId = {$tablet->iRTId} ");
//                    if (!$res) {
//                        echo '<font color="red">关联流程计划失败,申领id为:'.$tablet->iRTId.'</font><br>';
//                        continue;
//                    }
//                    echo  $schoolName[$tablet->iSchoolId].',更新成功<br>';
//                }
//            }
//        }
//        echo '学生机申请已全部更新完毕'.'<br>';
//    }

//	/**
//	 * 跑脚本修复设备维修沟通次数
//	 *
//	 *
//	 * create by qgz 20180704
//	 */
//    public function setDeviceCommTimesAction(){
//	    $data = XhsysDevicerepair::find([
//		    'columns' => 'iId, sCommContent, iCommTimes ',
//		    'conditions' => " bDelete = 0 AND sCommContent IS NOT NULL AND sCommContent != '' "
//	    ])->toArray();
//	    if (!$data){
//		    echo '没有需要插入的数据';
//	    }
//	    foreach ($data as $value) {
//		    $commContent = json_decode($value['sCommContent'], true);
//		    $times = $commContent['times'];
//		    $iId = $commContent['iId'];
//		    $sql2 = "update XHSys_DeviceRepair set iCommTimes = {$times} where bDelete = 0 AND iId = {$iId}";
//		    $data = $this->db->execute($sql2);
//		    if ($data) {
//			    echo "id:".$iId."设置成功，数量：".$times."<br/>";
//		    }
//	    }
//	    echo '全部设置成功';
//    }

//	/**
//	 * 脚本跑设备维修最近一次沟通时间
//	 *
//	 *
//	 * create by qgz 20180725
//	 */
//    public function setDeviceLatestDateAction(){
//	    $data = XhsysDevicerepair::find([
//		    'columns' => 'iId, sCommContent, iCommTimes ',
//		    'conditions' => " bDelete = 0 AND sCommContent IS NOT NULL AND sCommContent != '' "
//	    ])->toArray();
//	    if (!$data){
//		    echo '没有需要插入的数据';
//	    }
//	    foreach ($data as $value) {
//		    $commContent = json_decode($value['sCommContent'], true);
//		    if (empty($commContent)){
//		    	continue;
//		    }
//		    $iId = $commContent['iId'];
//		    $commData = $commContent['data'];
//		    $commData = max(array_column($commData, 'commDate'));
//		    $sql2 = "update XHSys_DeviceRepair set tLatestCommDate = '{$commData}' where bDelete = 0 AND iId = {$iId}";
//		    $data = $this->db->execute($sql2);
//		    if ($data) {
//			    echo "id:".$iId."设置成功，值：".$commData."<br/>";
//		    }
//	    }
//	    echo '全部设置成功';
//    }

//	/**
//	 * 迁移物品类型
//	 *
//	 *
//	 * create by qgz 20180724
//	 */
//    public function moveTypeTableAction(){
//    	$params = $this->request->getQuery('type');
//    	if ($params){
//		    $params = explode(',', $params);
//	    }else{
//		    $params = ['充电设备', '平板', '平板壳'];
//	    }
//	    $data = XHImsProdType::find(
//	    	[
//	    		'conditions' => 'sTypeName not in ({arr:array})',
//			    'bind' => ['arr' => $params]
//		    ]
//	    )->toArray();
//    	if (!$data){
//    		echo '没有需要转移的类型数据';die;
//	    }
//	    $this->db->begin();
//	    try {
//		    foreach ($data as $value){
//			    $sql = "insert into XHLm_GoodsType(iId,sTypeName,bDelete,tCreateDate,iCreateUserId,tLastModifyDate,iLastModifyUserId )
//VALUES({$value['iTypeId']},'{$value['sTypeName']}',{$value['bDelete']},'{$value['tCreateDate']}','{$value['iCreateUserId']}','{$value['tLastModifyDate']}', '{$value['iLastModifyUserId']}')";
//			    $run = $this->db->execute($sql);
//			    if (!$run){
//				    $this->db->rollback();
//				    echo '迁移出错，id：'.$value['iTypeId'].';名称：'.$value['sTypeName'];die;
//			    }
//			    echo '成功，id：'.$value['iTypeId'].';名称：'.$value['sTypeName']."<br/>";
//		    }
//		    $this->db->commit();
//		    echo '全部成功';
//	    } catch ( \Exception $e ) {
//		    $this->db->rollback();
//		    echo '出错：'.$e->getMessage();
//	    }
//    }
//
//	/**
//	 * 迁移商品表
//	 *
//	 *
//	 * create by qgz 20180724
//	 */
//    public function moveGoodsTableAction(){
//	    $typeData = $this->db->query('select iId from XHLm_GoodsType')->fetchAll(\PDO::FETCH_ASSOC);
//	    if (empty($typeData)){
//		    echo '没有类型数据';die;
//	    }
//	    $typeData = array_column($typeData,'iId');
//	    $findData = XHImsProduct::find([
//		    'conditions' => 'iTypeId in ({arr:array})',
//		    'bind' => ['arr' => $typeData]
//	    ])->toArray();
//	    if (!$findData){
//		    echo '没有物品数据';die;
//	    }
//	    $this->db->begin();
//	    try {
//		    foreach ($findData as $value){
//			    $sql = "insert into XHLm_Goods(iId, iGoodsType, sGoodsName, iUnit, bDelete, tCreateDate,iCreateUserId,tLastModifyDate,iLastModifyUserId )
//VALUES ({$value['iProdId']},'{$value['iTypeId']}','{$value['sProdName']}','{$value['sMeasures']}',{$value['bDelete']},'{$value['tCreateDate']}','{$value['iCreateUserId']}','{$value['tLastModifyDate']}','{$value['iLastModifyUserId']}')";
//			    $run = $this->db->execute($sql);
//			    if (!$run){
//				    $this->db->rollback();
//				    echo '迁移出错，id：'.$value['iProdId'].';名称：'.$value['sProdName'];die;
//			    }
//			    echo '成功，id：'.$value['iProdId'].';名称：'.$value['sProdName']."<br/>";
//		    }
//		    $this->db->commit();
//		    echo '全部成功';
//	    } catch ( \Exception $e ) {
//		    $this->db->rollback();
//		    echo '出错：'.$e->getMessage();
//	    }
//    }
//
//	/**
//	 * 迁移入库表
//	 *
//	 *
//	 * create by qgz 20180724
//	 */
//    public function moveGoodsInTableAction(){
//	    $goodsData = $this->db->query('select iId from XHLm_Goods')->fetchAll(\PDO::FETCH_ASSOC);
//	    if (empty($goodsData)){
//		    echo '没有物品数据';die;
//	    }
//	    $goodsData = array_column($goodsData,'iId');
//	    $findData = XHImsBoxIn::find([
//		    'conditions' => 'iProdId in ({arr:array})',
//		    'bind' => ['arr' => $goodsData]
//	    ])->toArray();
//	    if (!$findData){
//		    echo '没有物品数据';die;
//	    }
//	    $this->db->begin();
//	    try {
//		    foreach ($findData as $value){
//			    $inType = 1;
//			    $iInUserId = $value['iCreateUserId'];
//			    $tInTime = $value['tCreateDate'];
//			    if ($value['iLRTId']){//如果是归还
//				    $inType = 2;
//				    $returnData = XHImsReturn::findFirst(['conditions' => 'iLRTId = '.$value['iLRTId']]);
//				    if ($returnData){
//					    $returnData = $returnData->toArray();
//					    if ($returnData['iReturnId']){
//						    $iInUserId = $returnData['iReturnId'];
//					    }
//					    if ($returnData['tRealTime']){
//						    $tInTime = $returnData['tRealTime'];
//					    }
//				    }
//			    }
//			    $sql = "insert into XHLm_GoodsIn(iId, iGoodsId, iInPrice, tInTime, iInNum, iInType,iInTypeId,iInUserId,sRemark,bDelete, tCreateDate,iCreateUserId,tLastModifyDate,iLastModifyUserId)
//VALUES ({$value['iBoxId']},'{$value['iProdId']}','{$value['iInPrice']}', '{$tInTime}', '{$value['iProdNum']}',$inType,'{$value['iLRTId']}','{$iInUserId}','{$value['sRemark']}',{$value['bDelete']},'{$value['tCreateDate']}','{$value['iCreateUserId']}','{$value['tLastModifyDate']}','{$value['iLastModifyUserId']}')";
//			    $run = $this->db->execute($sql);
//			    if (!$run){
//				    $this->db->rollback();
//				    echo '迁移出错，id：'.$value['iBoxId'].';物品id：'.$value['iProdId'];die;
//			    }
//			    echo '成功，id：'.$value['iBoxId'].';物品id：'.$value['iProdId']."<br/>";
//		    }
//		    $this->db->commit();
//		    echo '全部成功';die;
//	    } catch ( \Exception $e ) {
//		    $this->db->rollback();
//		    echo '出错：'.$e->getMessage();
//	    }
//    }
//
//	/**
//	 * 迁移出库表数据
//	 *
//	 *
//	 * create by qgz 20180724
//	 */
//    public function moveGoodsOutTableAction(){
//	    $goodsData = $this->db->query('select iId from XHLm_Goods')->fetchAll(\PDO::FETCH_ASSOC);
//	    if (empty($goodsData)){
//		    echo '没有物品数据';die;
//	    }
//	    $goodsData = array_column($goodsData,'iId');
//	    $findData = XHImsBoxOut::find([
//		    'conditions' => 'iProdId in ({arr:array})',
//		    'bind' => ['arr' => $goodsData]
//	    ])->toArray();
//	    if (!$findData){
//		    echo '没有物品数据';die;
//	    }
//	    $this->db->begin();
//	    try {
//		    foreach ($findData as $value){
//			    $outType = 1;
//			    $iOutUserId = $value['iCreateUserId'];
//			    $tOutTime = $value['tCreateDate'];
//			    if ($value['iLRId']){//如果是申领
//				    $outType = 2;
//				    $returnData = XHImsReceive::findFirst(['conditions' => 'iLRId = '.$value['iLRId']]);
//				    if ($returnData){
//					    $returnData = $returnData->toArray();
//					    if ($returnData['iReceiveId']){
//						    $iOutUserId = $returnData['iReceiveId'];
//					    }
//					    if ($returnData['tRealTime']){
//						    $tOutTime = $returnData['tRealTime'];
//					    }
//				    }
//			    }
//			    $sql = "insert into XHLm_GoodsOut(iId, iGoodsId, tOutTime, iOutNum, iOutType,iOutTypeId,iOutUserId,sRemark,bDelete, tCreateDate,iCreateUserId,tLastModifyDate,iLastModifyUserId)
//VALUES ({$value['iBOutId']},'{$value['iProdId']}','{$tOutTime}', '{$value['iOutNum']}',$outType,'{$value['iLRId']}','{$iOutUserId}','{$value['sRemark']}',{$value['bDelete']},'{$value['tCreateDate']}','{$value['iCreateUserId']}','{$value['tLastModifyDate']}','{$value['iLastModifyUserId']}')";
//			    $run = $this->db->execute($sql);
//			    if (!$run){
//				    $this->db->rollback();
//				    echo '迁移出错，id：'.$value['iBoxId'].';物品id：'.$value['iProdId'];die;
//			    }
//			    echo '成功，id：'.$value['iBoxId'].';物品id：'.$value['iProdId']."<br/>";
//		    }
//		    $this->db->commit();
//		    echo '全部成功';die;
//	    } catch ( \Exception $e ) {
//		    $this->db->rollback();
//		    echo '出错：'.$e->getMessage();
//	    }
//    }

    /**
     * 设备申领bug处理
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale  20190110
     */
    public function deviceRunAction()
    {
        try {
            $applyTabObjArr = XHImsApplyTablet::find([
                'conditions' => 'bDelete = 0 and iSignState = 1 and iState = 3 ',
            ]);
            $doubleTeacherBindArr = [];
            $errorAuthArr = [];
            $errorProdArr = [];
            $errorApplySave = [];
            $successArr = [];
            foreach ($applyTabObjArr as $applyTabObj) {
                $mTchCode = $applyTabObj->mTchCode;
                $teachers = $applyTabObj->sTeachers;
                if (!is_array($mTchCode)) {
                    $mTchCode = unserialize($mTchCode) ?: [];
                }
                $teachers = array_values(array_filter(explode(',', $teachers)));
                $errorTeachers = [];
                if ($teachers) {  //获取缺少信息的教师
                    if ($mTchCode) {
                        foreach ($teachers as $teacherId) {
                            $prodId =  @$mTchCode[$teacherId]['iProdId'];
                            if ($prodId) {
                                continue;
                            }
                            $errorTeachers[] = $teacherId;
                        }
                    }
                }
                if ($errorTeachers) {
//                    var_dump($errorTeachers);die;
                    foreach ($errorTeachers as $teacherId) { //遍历
                        $sql = "select iUserId,sLogonName,sDeviceNumber,sModel from XHSys_AccountDeviceLocked 
                               where iUserId = '{$teacherId}' and bDelete = 0 ";
                        $data = $this->db->fetchAll($sql);
                        if (!$data) {
                            continue;
                        }
                        if (count($data) != 1) {
                            $doubleTeacherBindArr[] = $teacherId;
                            continue;
                        }
                        $bindInfo = $data[0];
                        $checkSql = "select iUTId from XHSys_UserTablet where iReceiveStatus = 2 
                                      and sDevNumber = '{$bindInfo['sDeviceNumber']}' and bDelete = 0 ";
                        $check = $this->db->fetchAll($checkSql);
                        if (!$check) {
                            $errorAuthArr[] = $bindInfo['sDeviceNumber'];
                            continue;
                        }
                        $prodInfo = XHImsProduce::findFirst([
                            'columns'    => 'iProdId',
                            'conditions' => 'bDelete = 0 and sProdName = :sProdName:',
                            'bind'       => ['sProdName' => $bindInfo['sModel']]
                        ]);
                        if (!$prodInfo) {
                            $errorProdArr[] = $bindInfo['sModel'];
                            continue;
                        }
                        $mTchCode[$teacherId] = ['iProdId' => $prodInfo->iProdId, 'code' => $bindInfo['sDeviceNumber']];
                        $successArr[$applyTabObj->iRTId][] = ['tchId' =>$teacherId, 'iProdId' => $prodInfo->iProdId, 'code' => $bindInfo['sDeviceNumber']];
                    }
                    $applyTabObj->mTchCode = $mTchCode;
                    if (!$applyTabObj->save(null, null, false)) {
                        $errorApplySave[] = $applyTabObj->toArray();
                        continue;
                    }
                }
            }
            $this->createCommitLog('执行成功',[
                'doubleTeacherBindArr' => $doubleTeacherBindArr,
                'errorAuthArr' => $errorAuthArr,
                'errorProdArr' => $errorProdArr,
                'errorApplySave' => $errorApplySave,
                'successArr' => $successArr
            ]);
            return $this->sendSuccessResponse('执行成功');
        } catch (\Exception $e) {
            return $this->sendErrorResponse(
                500,
                $e->getMessage(),
                $e instanceof XhException ? $e->getDescription() : $e->getTrace()
            );
        }
    }

    /**
     *
     * 设备授权列表自动同步数据，每天一次
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     * @throws \Exception
     *
     * create by qgz 20190129
     */
    public function synRegisterAction()
    {
        $data = XhsysUsertablet::find([
            'columns' => 'iUTId, sDevNumber, sMacAddress, sDevType, sIMei',
            'conditions' => "bDelete = 0 and sDevNumber is not null and sDevNumber != '' and (sDevType is null or sDevType = '' or sDevType = 'Normal') "
        ])->toArray();//只找出设备型号为空的进行同步，否则数据太大脚本太慢
        if (!$data){
            return $this->sendSuccessResponse('没有需要同步的数据');
        }
        $noLoginNum = $noChange = 0;
        $change = ['fail' => [], 'success' => []];
        foreach($data as $value){
            $isChange = false;
            $XhsysUsertablet = XhsysUsertablet::findFirst(['columns' => '*', 'conditions' => "bDelete = 0 and iUTId = ".$value['iUTId']]);
            $login_data = LoginLog::findFirst([
                'columns' => 'lo_id, lo_us_id, lo_uid, lo_computername, lo_mac, lo_model, lo_imei',
                'conditions' => "lo_computername = '".$value['sDevNumber']."'",//根据设备号查询
                'order' => 'lo_date DESC'
            ]);
            if (!$login_data){
                $noLoginNum++;
                $noChange++;
                $change['success'][] = $value;
                continue;
            }
            $login_data = $login_data->toArray();
            if ($login_data['lo_mac'] && ($login_data['lo_mac'] != $value['sMacAddress'])){
                $XhsysUsertablet->sMacAddress = $login_data['lo_mac'];
                $isChange = true;
            }
            if ($login_data['lo_model'] && ($login_data['lo_model'] != $value['sDevType'])){
                $XhsysUsertablet->sDevType = $login_data['lo_model'];
                $isChange = true;
            }
            if ($login_data['lo_imei'] && ($login_data['lo_imei'] != $value['sIMei'])){
                $XhsysUsertablet->sIMei = $login_data['lo_imei'];
                $isChange = true;
            }
            if ($isChange){
                $sql = "update XHSys_UserTablet set sMacAddress = '{$login_data['lo_mac']}', sDevType = '{$login_data['lo_model']}', sIMei = '{$login_data['lo_imei']}' where iUTId = {$value['iUTId']}";
                $final = $this->db->execute($sql);
                if (!$final){
                    $value['reason'] = '同步失败：id：' . $value['iUTId'];
                    $change['fail'][] = $value;
                    continue;
                }else{
                    $change['success'][] = $value;
                }
            }else{
                $noChange++;
                $change['success'][] = $value;
            }
            unset($XhsysUsertablet, $login_data);
        }
        unset($data);
        $msg = '成功'.count($change['success']).'台;';//成功的数量
        if ($noChange != 0){
            $msg .= '[包括未改变' . $noChange . '台];';//数据未改变
        }
        if ($noLoginNum != 0){
            $msg .= '[包括找不到可同步数据' . $noLoginNum . '台];';//日志表找不到数量
        }
        if(count($change['fail']) > 0){
            $msg .= '失败' . count($change['fail']) . '台;';//失败的数量
        }
        $return = [
            'msg' => $msg,
            'noFindNum' => $noLoginNum,
            'successNum' => count($change['success']),
            'errorNum' => count($change['fail']),
            'errorData' => $change['fail']//失败的数据
        ];
        return $this->sendJsonResponse($return, true);
    }
}

